天天看点

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},去掉默认自动配置类的扫码。如果没有自定义图片上传配置类,请保留。

继续阅读