Loading

SpringMVC文件上传

相关依赖

使用 SpringMVC 提供的文件上传需要在项目中加入两个 jar 包,对应的 maven 的依赖分别是:commons-iocommons-fileupload

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

<dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

SpringMVC 配置文件

SpringMVC 的配置文件中需要注入 SpringMVC 支持文件上传的类 CommonsMultipartResolver 的 Bean,Bean 的 id 为 multipartResolver,该 id 是固定的,SpringMVC 在加载时会去容器查找该 id 的 Bean,若容器中存在该 id,则支持文件上传,若不存在,则不支持文件上传

前端异步请求文件上传

//html代码
图片上传:<input type="file" name="file1" multiple="multiple" id="file0" />
<img src="" id="img0">
<button id="ajax_upload">Ajax上传</button>

//js 代码
$("#file0").change(function () {
            var formData = new FormData();
            formData.append("file",document.getElementById("file0").files[0]);
            $.ajax({
                url : "ajaxUpload",
                data : formData,
                type : "post",
                contentType:false,
                processData:false,
                dataType : "json",
                success : function(response){
                    if(response.dataState == "success"){
                        // 为 src 属性设置上传文件的相对路径,实现文件预览
                        $("#img0").attr("src",response.responseMap["fileUrl"]);
                    }else{
                        alert(response.dataState);
                    }
                }
            });
        });

注意:ajax 发起文件上传的请求时需要将 contentTypeprocessType 都设置为 false

后台 controller 实现

使用 SpringMvc 实现文件上传时,Congtroller 需要指定 MultipartFile 类型的参数来接收前端传来的文件数据

@RequestMapping(value = "ajaxUpload",produces = {"text/html;charset=UTF-8;","application/json;"})
    @ResponseBody
    public ResponseResult ajaxUplod(ResponseResult responseResult, MultipartFile file, HttpServletRequest request){
        // 获取上传文件的原始名称
        String fileName = file.getOriginalFilename();
        // 获取上传文件的后缀名
        String ext = fileName.substring(fileName.lastIndexOf("."));
        // 获取当前项目资源文件的绝对路径
        StringBuilder stringBuilder1 = new StringBuilder(request.getSession().getServletContext().getRealPath("/"));
        String baseUrl = stringBuilder1.toString();
        // 设置本地文件的相对路径
        StringBuilder stringBuilder2 = new StringBuilder(File.separator);
        stringBuilder2.append("upload");
        stringBuilder2.append(File.separator);
        stringBuilder2.append(Calendar.YEAR);
        stringBuilder2.append("-");
        stringBuilder2.append(Calendar.MONTH);
        stringBuilder2.append("-");
        stringBuilder2.append(Calendar.DATE);
        stringBuilder2.append(ext);
        String fileUrl = stringBuilder2.toString();
        // 当前项目路径 + 文件存储的相对路径 = 上传文件存储的绝对路径
        File localFile = new File(stringBuilder1.append(stringBuilder2).toString());
        Map<String,Object> map = new HashMap();
        // 将文件的相对路径返回给前端实现文件预览
        map.put("fileUrl",fileUrl);
        if(!localFile.exists()){
            localFile.mkdirs();
        }
        try {
            file.transferTo(localFile);
            responseResult.setDataState("success");
            responseResult.setMsg("上传成功");
            responseResult.setResponseMap(map);
        } catch (IOException e) {
            responseResult.setDataState("fail");
            responseResult.setMsg("上传失败");
            e.printStackTrace();
        }
        return responseResult;
    }

注意:

  1. 若上传的文件只需保存在当前项目的目录中,可以使用上述方法,若需保存在单独的图片服务器中,则需要指定服务器的访问路径,该路径最好是写在配置文件中
  2. 单独将相对路径提取出来返回给前端是为了前端能预览上传的文件,若没有这种需求,可以忽略此步骤
  3. transferTo 方法是 springMVC 提供的复制文件的方法,该方法将file 文件的内容写入到指定的文件中去,省略来手动进行文件复制的流操作
posted @ 2023-07-17 15:54  赵妹儿  阅读(43)  评论(0编辑  收藏  举报