ssm框架之Springmvc中文件上传

一、上传:

1)编写前台文件上传表单。Method必须为post,enctype为mutipart/form-data

<body>
<%--文件上传
     1)method必须指定为post
     2)enctype必须指定为multipart/form-data
--%>
<h1>头像上传</h1>
<form action="${pageContext.request.contextPath}/admin/headpic" method="post" enctype="multipart/form-data">
    选择头像:<input type="file" name="headpic"/>
<%--    ${param.属性值}==request.getParameter(属性值)--%>
    <input type="text" name="id" value="${param.id}">
    <input type="submit" value="上传"/>
</form>
</body>

2)编写控制层代码,获取上传的文件数据,并保存MultipartFile;

     //MultipartFile:用来接收上传的文件,参数名与input的name一直
    //@SessionAttribute("admin"):获取session域中的值
    //@RequestParam(required = false):指定对应的参数可以为空,不是必须有值
    @RequestMapping("/headpic")
    public String headPic(MultipartFile headpic,@RequestParam(required = false) Admin admin,Integer id) throws IOException {
        String filename = headpic.getOriginalFilename();
        System.out.println("上传的文件名:"+filename);
        File file=new File("E:/headpic/"+filename);
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdirs();//如果父目录不存在,创建该目录
        }
        //保存文件,将上传的文件内容写入file
        headpic.transferTo(file);
        admin=new Admin(id);
        //将头像访问路径保存到对象中
        admin.setHeadpic("/head/"+filename);
        //更新用户头像信息
        adminService.updateHeadPic(admin);
        return "redirect:list";
    }

3)在springmvc配置文件中配置文件上传配置项。配置multipartResolver;

   <!--配置文件上传-->
    <bean id="multipartResolver"
          class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--设置文件编码格式-->
        <property name="defaultEncoding" value="UTF-8"/>
        <!--设置最大上传大小-->
        <property name="maxUploadSize" value="10240000" />
    </bean>
<!--    资源映射,将请求地址映射到某个目录或具体的磁盘路径
mapping:配置请求地址; location:配置文件路径
请求地址:/head/logo.png==>E:/headpic/logo.png
-->
<mvc:resources mapping="/head/**" location="file:E:/headpic/"></mvc:resources>
<!-- 请求地址为/headimg/logo.png==>/WEB-INF/img/logo.png-->
<mvc:resources mapping="/headimg/**" location="/WEB-INF/img/"></mvc:resources>

二、下载:

1) 获取到下载文件的路径;

2) 读取文件内容到字节数组;

3) 返回字节数组,并声明返回类型为stream,设置附件名称;

 @GetMapping("/headPicDownload")
    public ResponseEntity<byte[]> headPicDownload(String filename) throws IOException {
        //1、定位到文件地址
        File file=new File("E:/headpic/"+filename);
        //2、读取文件内容
        byte[] bytes= FileUtils.readFileToByteArray(file);
        //3、设置http响应头
        HttpHeaders headers = new HttpHeaders();
        //设置ContentType为stream
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        //4、设置以附件形式打开
        headers.setContentDispositionFormData("attachment",filename);
        //                                内容   头部信息   http状态码
        return new ResponseEntity<byte[]>(bytes,headers, HttpStatus.CREATED);
    }
             <td>
                <img style=" 25px;height: 25px;border-radius: 50%;"
                     src="${pageContext.request.contextPath}${admin.headpic}"/>
                <a href="${pageContext.request.contextPath}/admin/headPicDownload?filename=${fn:replace(admin.headpic,"/head/","" )}">下载</a>
            </td>
原文地址:https://www.cnblogs.com/xie-qi/p/13090656.html