springmvc中的文件下载以及文件上传

1.图片下载
ResponseEntity结果图片下载

@RequestMapping("/testDown")
public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException{
    //获取容器对象
    ServletContext servletContext = session.getServletContext();
    //获取真实路径
    String realPath = servletContext.getRealPath("/static/img/xiaoniao.png");
    //创建输入流
    InputStream is = new FileInputStream(realPath);
    //创建HttpHeaders对象设计响应头信息
    MultiValueMap<String,String> headers = new HttpHeaders();
    //设置要下载方法以及下载文件的名字
    headers.add("Content-Disposition","attachment;filename=xiaoniao.png");
    //设置状态码
    HttpStatus statusCode = HttpStatus.OK;
    //读数据到流
    byte[] bytes = new byte[is.available()];
    is.read(bytes);
    //创建对象
    ResponseEntity<byte[]> responseEntity = new ResponseEntity(bytes, headers, statusCode);
    is.close();
    return responseEntity;

}

2.图片上传
图片上传必须是post,配置mvc图片上传解析器,别忘记加id,springmvc容器默认是看id匹配

<!--文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="UTF-8"></property>
    <property name="maxInMemorySize" value="500000"></property>
</bean>

前端代码

<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
    头像:<input type="file" name="photo"><br>
    <input type="submit" value="上传">
</form>

使用uuid解决文件上传重名问题

@RequestMapping("/testUp")
    public String testUp(MultipartFile photo,HttpSession session) throws IOException {
        //上传
        //System.out.println(photo.getOriginalFilename());//获取图片的名字

        //获取文件名
        String fileName = photo.getOriginalFilename();
        //获取图片名字的后缀
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //将UUID作为文件名
        String uuid = UUID.randomUUID().toString();
        //拼接后的结果
        fileName = uuid+suffixName;
        ServletContext servletContext = session.getServletContext();

        String realPath = servletContext.getRealPath("/static/img");
        File file = new File(realPath);
        if(!file.exists()){
            file.mkdirs();
        }
        String finalPath = realPath+ File.separator+fileName;
        photo.transferTo(new File(finalPath));//上传
        return "success";
    }
上一篇:SpringMVC中Controller层的接口的一些不同写法总结


下一篇:SpringMvc---视图解析器、视图控制器