SpringMVC实现图片上传

1.添加pom依赖

<!-- 图片上传依赖 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

2.在SpringMVC配置文件中配置文件解析器

<!-- 文件上传解析器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 上传文件最大的大小 -->
        <property name="maxUploadSize" value="41300260"></property>
        <!-- 字符编码 -->
        <property name="defaultEncoding" value="utf-8"></property>
    </bean>

3.创建上传文件控制器UploadController

@RestController
public class UploadController {
    @PostMapping("/upload")
    @PassToken
    public ResponseResult upload(MultipartFile file, MultipartHttpServletRequest request) throws IOException {
        Map data = null;
        if(file != null){
            String type = null;//文件类型
            String fileName=file.getOriginalFilename();// 文件原名
            System.out.println("上传的源文件名称:"+fileName);
            type=fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
            if(type != null){
                if("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())){
                    // 硬盘中存放图片的路径
                    String realPath="D:\\develop\\tomcat\\apache-tomcat-8.5.40\\upload\\tmp_uploads\\";
                    // 自定义的文件名称
                    String trueFileName=String.valueOf(System.currentTimeMillis())+fileName;
                    //项目发布时图片请求路径
                    String tmpPath = "tmp_uploads/"+trueFileName;
                    // 设置存放图片文件的完整路径
                    String path=realPath+trueFileName;
                    System.out.println("图片存储的路径是:"+path);
                    // 保存文件到硬盘中
                    file.transferTo(new File(path));
                    data = new HashMap<String,Object>();
                    data.put("tmp_path",tmpPath);
                    data.put("url","127.0.0.1:8090/"+tmpPath);
                    return new ResponseResult(data, 200, "上传成功");

                }else {
                    return new ResponseResult(data, 500, "文件类型错误");
                }
            }else{
                return new ResponseResult(data, 500, "文件类型为空");
           }
        }else{
            return new ResponseResult(data, 500, "没有找到相对应的文件");

        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值