天天看點

springboot 實作圖檔上傳功能

環境介紹

springboot 版本2.1.3

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath />
</parent>      

實作圖檔MultipartFile 上傳 需添加相應依賴

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <!-- 移除嵌入式tomcat插件 -->
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>      

如果導入了spring-boot-starter-web依賴,則可以不在使用一下依賴

<!--  <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.5</version>
        </dependency>-->
<!--        <dependency>-->
<!--            <groupId>commons-fileupload</groupId>-->
<!--            <artifactId>commons-fileupload</artifactId>-->
<!--            <version>1.4</version>-->
<!--            <exclusions>-->
<!--                <exclusion>-->
<!--                    <groupId>commons-io</groupId>-->
<!--                    <artifactId>commons-io</artifactId>-->
<!--                </exclusion>-->
<!--            </exclusions>-->
<!--        </dependency>-->      

資源大小限制

spring:
  servlet:
    multipart:
      enabled: true
      max-file-size: 100MB
      max-request-size: 100MB      

springboot 2.0以上版本 不在使用springboot.http.multipart。

圖檔上傳接口

@RequestMapping(value = "upload", method = RequestMethod.POST)
    @Log("上傳")
    public void uploadOrder(MultipartHttpServletRequest multipartRequest, HttpServletResponse response)
            throws Exception {
        String result = "";
        Map map = new HashMap<>();
        try {
            for (Iterator it = multipartRequest.getFileNames(); it.hasNext(); ) {
                String key = (String) it.next();
                MultipartFile orderFile = multipartRequest.getFile(key);
                if (orderFile.getOriginalFilename().length() > 0) {
                              //儲存路徑
                    String realPath="C:\Users\pic";
                    String origfilename = orderFile.getOriginalFilename();                    //檔案原始名
                    Long size = orderFile.getSize();
                    String suffix = origfilename.substring(origfilename.lastIndexOf(".") + 1);    //檔案字尾 不包含.
                    String currfilename = UUID.randomUUID().toString() + "." + suffix;            //儲存檔案名
                    ByteUtils.saveToImgByte(orderFile.getBytes(), realPath, currfilename);          //執行儲存
                }
            }
            response.getWriter().print("{code:001;result:上傳成功}");
        } catch (Exception ex) {
            ex.printStackTrace();
            response.getWriter().print("{code:500;result:上傳失敗:"+ex.getMessage()+"}");
        }

    }      

ByteUtils 工具類

public static int saveToImgByte(byte[] imgByte, String imgPath, String imgName) {
    int stateInt = 1;
    InputStream in = null;
    FileOutputStream fos = null;

    try {
        in = new ByteArrayInputStream(imgByte);
        File mark = new File(imgPath);
        if (!mark.exists()) {
            mark.mkdirs();
        }

        File file = new File(imgPath, imgName);
        fos = new FileOutputStream(file);
        byte[] b = new byte[1024];
        boolean var9 = false;

        int nRead;
        while((nRead = in.read(b)) != -1) {
            fos.write(b, 0, nRead);
        }
    } catch (Exception var18) {
        stateInt = 0;
        var18.printStackTrace();
    } finally {
        try {
            fos.flush();
            fos.close();
            in.close();
        } catch (IOException var17) {
            var17.printStackTrace();
        }

    }

    return stateInt;
}      

常見問題處理

前端通過form-data上傳的參數,背景使用 @RequestParam 接受不到前端傳遞的參數

問題排查路線

springboot自帶圖檔上傳處理類,如果自己編寫了圖檔上傳元件實作MultipartResolver接口,

請在啟動類@SpringBootApplication(exclude = {MultipartAutoConfiguration.class},去掉預設自動配置類的掃碼。如果沒有自定義圖檔上傳配置類,請保留。

繼續閱讀