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;
}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐