@PostMapping("/upload")
public AjaxResult uploadFile(@RequestBody JSONObject blobPath) throws Exception
{
String blobPath1 = blobPath.getStr("blob");
MultipartFile file = convertToMultipartFile(blobPath1);
if(file==null){
return AjaxResult.error("网络异常,请稍后尝试");
}
try
{
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
AjaxResult ajax = AjaxResult.success();
ajax.put("fileName", fileName);
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
public MultipartFile convertToMultipartFile(String filePath) throws IOException {
File file = new File(filePath);
String s = Files.probeContentType(file.toPath());
System.out.println("s = " + s);
String name = file.getName();
System.out.println("name = " + name);
int length = (int) file.length();
File parentFile = file.getParentFile();
FileItem fileItem = new DiskFileItem("copyfile.txt", s,false, name, length, parentFile);
byte[] buffer = new byte[4096];
int n;
MultipartFile multipartFile = null;
try (InputStream inputStream = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()){
while ( (n = inputStream.read(buffer,0,4096)) != -1){
os.write(buffer,0,n);
}
multipartFile = new CommonsMultipartFile(fileItem);
System.out.println(multipartFile.getName());
}catch (IOException e){
e.printStackTrace();
}
return multipartFile;
}
绝对路径文件上传
最新推荐文章于 2024-10-09 11:47:41 发布