图片上传过程

时间:2022-09-03 20:51:01

1、把commons-iofileupload jar包添加到工程中。(pom文件中添加依赖即可)

2、在表现层(taotao-web)springmvc.xml文件中配置多媒体解析器

<!-- 定义文件上传解析器 -->

<bean id="multipartResolver"

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

<!-- 设定默认编码 -->

<property name="defaultEncoding" value="UTF-8"></property>

<!-- 设定文件上传的最大值5MB,5*1024*1024 -->

<property name="maxUploadSize" value="5242880"></property>

</bean>

 

3、上传图片:

 

package cn.e3mall.controller;

import cn.e3mall.common.util.FastDFSClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * 图片上传Controller
 */
@Controller
public class PictureController {

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

    @RequestMapping("/pic/upload")
    @ResponseBody
    public Map uploadFile(MultipartFile uploadFile){
        try{
            //上传文件
            FastDFSClient fastDFSClient = new FastDFSClient("classpath:conf/client.conf");
            //获取到文件的原名称(原名称中包含文件扩展名)
            String originalFilename = uploadFile.getOriginalFilename();
            //获取文件扩展名(originalFilename.lastIndexOf(".")表示从"."开始,包含"."
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //根据返回的String拼好完整的路径名(第一个参数是上传文件的字节数组,第二个参数是文件的扩展名)
            String string = fastDFSClient.uploadFile(uploadFile.getBytes(), extName);
            //拼接路径(http://192.168.1.142/+string
            String url = IMAGE_SERVER_URL+string;
            //装到Map中返回
            Map map = new HashMap();
            map.put("error",0);
            map.put("url",url);
            return map;
        }catch(Exception e){
            //先打印异常信息
            e.printStackTrace();
            //出现异常说明上传失败了
            Map map = new HashMap();
            map.put("error",1);
            map.put("message","上传失败了");
            return map;
        }

    }
}

 

需要用到的jar包还有工具类:

1、commons-fileupload.jar(版本我用的1.3.1)

2、下面这个需要properties文件,参考上条博客

    @Value("${IMAGE_SERVER_URL}")
    private String IMAGE_SERVER_URL;

3、FastDFSClient工具类:

链接:https://pan.baidu.com/s/1fzRDPD3ij7srJS3eJsxaHg
提取码:6cxt