前言: 我使用nginx 在阿里云服务器上搭建了静态资源文件服务器。
下面是实现上传的代码。 uploadController
@CrossOrigin
@PostMapping(value = "upload")
public RespBean upload(@RequestParam("file") MultipartFile file,Integer sid , Integer aid ,String uid) {
if (file.isEmpty()) {
return new RespBean(400, "请选择文件", null);
}
String fileName = file.getOriginalFilename();
String [] fileSuffix = file.getContentType().split("/");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
String key;
if (PictureType.isInclude(fileSuffix[1])) {
byte[] uploadBytes;
Map<String, String> map = new HashMap<>();
if (file.getSize() >= 5 * 1024 * 1024) {
try {
Thumbnails.of(file.getInputStream())
.scale(1f)
.outputQuality(0.5f)
.outputFormat("jpg")
.toOutputStream(outputStream);
uploadBytes = outputStream.toByteArray();
fileName = SHA.SHA256(outputStream);
map = QiNiuPicture.upload(fileName, uploadBytes);
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.println("图片压缩失败");
}
} else {
try {
uploadBytes = file.getBytes();
outputStream.write(uploadBytes);
fileName = SHA.SHA256(outputStream);
map = QiNiuPicture.upload(fileName, uploadBytes);
} catch (IOException | NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
if (map.containsKey("key")) {
key = map.get("key");
String outerChain = QiNiuPicture.outerChainBuild(key);
if (outerChain == null) {
return easyRespBean.err();
}
return easyRespBean.ok(outerChain);
}
} else {
String url = baseUrl + uid+"/"+fileSuffix[0]+"/" + fileName ;
try {
createDir(uid+"/"+fileSuffix[0]);
File dest = new File(filePath+ uid+"/"+fileSuffix[0] +"/"+ fileName);
file.transferTo(dest);
int result = fileService.upLoadFile(fileName,url,fileSuffix[0],uid,aid,sid);
if(result == 0)
return easyRespBean.ok(url);
else
return easyRespBean.errWithMsg("上传失败");
} catch (IOException e) {
e.printStackTrace();
return easyRespBean.errWithMsg("上传失败");
}
}
return easyRespBean.errWithMsg("上传失败");
}
这可以实现在nginx配置的根目录,按照文件类型放置上传的文件。
|