
导入依赖
commons-fileupload
commons-fileupload
1.3.3
controller
package com.lixianhe.controller;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
/**
* @author 李显赫
* @Date 2022-05-05 23:15
*/
@RestController
public class UploadController {
@RequestMapping(value = "/load", method = RequestMethod.POST, consumes ="multipart/form-data")
public String getFile(@RequestParam("file") MultipartFile file) throws IOException {
System.out.println("收到请求");
if (file.isEmpty()) {
return "上传失败,请选择文件";
}
String fileName=file.getOriginalFilename();
//String fileName = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
System.out.println("文件名为:"+fileName);
assert fileName != null;
String suffixName = fileName.substring(fileName.lastIndexOf("."));
System.out.println("文件的后缀名为:" + suffixName);
String newfileName= UUID.randomUUID().toString()
.replaceAll("-", "")
.toUpperCase()
+System.currentTimeMillis()
+suffixName;
System.out.println("新的名称->"+newfileName);
ClassPathResource resource = new ClassPathResource("static");
String path = resource.getFile().getAbsolutePath();
File dest = new File(path+ "\\" + newfileName);
System.out.println(dest);
try {
file.transferTo(dest);
System.out.println("上传成功");
return newfileName;
} catch (IOException e) {
System.out.println("上传失败");
System.out.println(e.getMessage());
}
return "上传失败!";
}
}
测试
设置请求头
设置请求数据是文件类型
结果:上传成功
收到请求
文件名为:aMXyhAzKyCJe9f9558bca12106c8360b89e900043b2d.png
文件的后缀名为:.png
新的名称->B7527AD5D1F34F80963CA9E593ECB66E1651811072581.png
C:\Users\86131\Desktop\hospital\hospital\hospital\hospital-user\target\classes\static\B7527AD5D1F34F80963CA9E593ECB66E1651811072581.png
上传成功欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)