提供相关JAVA上传附件代码
kuhnpeng opened this issue · 0 comments
kuhnpeng commented
可上传图片,视频及其他文件,支付多个上传。
FileController.java
@PostMapping("/uploadFile")
public R uploadFile(HttpServletRequest request){
UploadFileResponse uploadFileResponse = null;
// 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
// 检查form中是否有enctype="multipart/form-data"
if (multipartResolver.isMultipart(request)) {
// 将request变成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// 获取multiRequest 中所有的文件名
Iterator iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 一次遍历所有文件
MultipartFile file = multiRequest.getFile(iter.next()
.toString());
//传递参数值
// String str = multiRequest.getParameter("str");
// System.out.println("str:" + str);
if (Objects.nonNull(file)) {
uploadFileResponse = fileService.storeSingleFile(file);
}
}
}
return R.OK().setData(uploadFileResponse);
}
FileService.java
* 存储文件到系统
*
* @param file 文件
* @return 文件名
*/
public UploadFileResponse storeSingleFile(MultipartFile file) {
String extension = FilenameUtils.getExtension(file.getOriginalFilename());
String fileName = FilenameUtils.getName(file.getOriginalFilename());
if(fileName.contains("..")) {
throw new FileException("Sorry! Filename contains invalid path sequence " + fileName);
}
try {
Path targetLocation = this.fileStorageLocation.resolve(fileName);
Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
return new UploadFileResponse(file.getName(),fileName,extension,file.getSize());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}