Maven pom 添加依赖包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
@PostMapping("/upload")
public String upload() throws IOException {
File file = new File("C:\\Users\\cocboo\\Desktop\\test.xlsx");
FileItem fileItem = this.getMultipartFile(file, "test");
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
// 上传到AliyunOSS
String url = ossFileUtils.upload(multipartFile.getOriginalFilename(), multipartFile);
return url;
}
// 调用
private FileItem getMultipartFile(File file, String fieldName) {
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(fieldName, "text/plain", true, file.getName());
int bytesRead = 0;
int len = 8192;
byte[] buffer = new byte[len];
try {
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, len)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
return item;
}