使用MultipartFile 做文件上傳的功能


使用 MultipartFile

准備表單

<body>
    <form enctype="multipart/form-data" method="post" action="/upload">
        文件:<input type="file" name="head_img"/>
        姓名:<input type="text" name="name"/>
        <input type="submit" value="上傳"/>
    </form>
</body>

 

控制器

import net.xdclass.demo.domain.JsonData;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileController {

    private static final String filePath = "D:\\IdeaProjects\\xdclass_springboot\\src\\main\\resources\\static\\images\\";

    @PostMapping(value = "/upload")
    public JsonData upload(
            @RequestParam(value = "head_img") MultipartFile file,
            HttpServletRequest request) {

        // 表單的 name="name" 屬性
        String name = request.getParameter("name");
        // 上傳的文件名
        String filename = file.getOriginalFilename();
        String suffixName = filename.substring(filename.lastIndexOf("."));

        // 隨機生成
        filename = UUID.randomUUID() + suffixName;
        File dest = new File(filePath + filename);

        try {
            file.transferTo(dest);
            return new JsonData(0, dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new JsonData(-1, null, "faild to save");

    }

}

 

  MultipartFile 對象的transferTo方法,用於文件保存(效率和操作比原先用FileOutStream方便和高效)。

 

  訪問 http://localhost:8080/upload.html,結果如下。

{
"code": 0,
"data": "D:\\IdeaProjects\\xdclass_springboot\\src\\main\\resources\\static\\images\\611fbdd7-95c5-4803-8c6f-796cccf6d2be.jpg",
"msg": null
}

  

  查看上傳的圖片。

http://localhost:8080/images/611fbdd7-95c5-4803-8c6f-796cccf6d2be.jpg

 

 

考慮1:限制文件大小

思路:自定義 createMultipartConfig。放在啟動類里也可以。

 

@Bean
public MultipartConfigElement multipartConfigElement() {
    MultipartConfigFactory factory = new MultipartConfigFactory();
    //單個文件最大
    factory.setMaxFileSize(DataSize.ofMegabytes(300));
    /// 設置總上傳數據總大小
    factory.setMaxRequestSize(DataSize.ofGigabytes(1));
    return factory.createMultipartConfig();
}

 

考慮2:自定義上傳文件的保存路徑

避免硬編碼,思路:寫成 配置文件,讀取出來。

參考我的 “讀取配置文件”,https://www.cnblogs.com/wuyicode/p/11249913.html 。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM