今天在一个业务服务通过Feign调用文件服务上传文件时遇到了几个问题:
1. 提示http请求头过大的问题;
- 此时需要修改bootstrap.yml,加入
server:
max-http-header-size: 10000000
用以放大尺寸
2. 调用方法时提示404,无返回结果;
- 解决方法:把控制器的注解由@Controller变为@RestController,就可以
被调用方具体代码如下:
@Slf4j
@RestController
@RequestMapping("/image")
public class ImageController {
private static List<String> allowUploadSuffixes = new ArrayList<>(Arrays.asList("png", "jpg", "jpeg", "zip", "pdf", "xls", "xlsx", "rar", "doc", "docx"));
@Autowired
private UploadFileEntityMapper uploadFileEntityMapper;
@RequestMapping(value = "/uploadBase64", method = RequestMethod.POST)
@ApiOperation(value = "通过base64方式上传文件")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "form", name = "appId", dataType = "String", required = true, value = "应用ID"),
@ApiImplicitParam(paramType = "form", name = "group", dataType = "String", required = true, value = "对应配置中心配置上传组名(如:public,private等)"),
@ApiImplicitParam(paramType = "form", name = "fileName", dataType = "String", required = true, value = "文件原名称"),
@ApiImplicitParam(paramType = "form", name = "file", dataType = "String", required = true, value = "文件内容")
})
public ApiResult<UploadResult> uploadBase64(@RequestParam("file") String file, @RequestParam(value = "appId") String appId, @RequestParam("group") String group, @RequestParam("fileName") String originFileName) {
String imageBase64Str;
String suffix;
String mime;
if (StringUtils.isBlank(file)) {
return new ApiResult<>(new UploadResult());
} else if (file.indexOf("data:image/png;") != -1) {
imageBase64Str = file.replace("data:image/png;base64,", "");
suffix = "png";
mime = "image/png";
} else if (file.indexOf("data:image/jpeg;") != -1) {
imageBase64Str = file.replace("data:image/jpeg;base64,", "");
suffix = "jpeg";
mime = "image/jpeg";
} else {
return new ApiResult<>(new UploadResult());
}
try {
if (!allowUploadSuffixes.contains(suffix)) {
throw new IotBaseException(9999, "不允许上传该文件类型");
}
String fileKey = UUID.randomUUID().toString() + "." + suffix;
FileSystemClient client = FileSystemClient.getClient(group);
String url = client.upload(fileKey, Base64.getDecoder().decode(imageBase64Str), appId, originFileName);
UploadFileEntity entity = new UploadFileEntity();
entity.setAppId(appId);
entity.setGroupName(group);
entity.setFileName(originFileName);
entity.setFileUrl(url);
entity.setMimeType(mime);
entity.setProvider(client.getProvider().name());
entity.setCreatedAt(new Date());
uploadFileEntityMapper.insert(entity);
return new ApiResult<>(new UploadResult(url, originFileName));
} catch (Exception e) {
e.printStackTrace();
throw new IotBaseException(ExceptionCode.SYSTEM_ERROR.code, "上传失败");
}
}
}