SpringMVC之文件上传、下载

一. springmvc的文件上传

  1.添加文件上传相关依赖
      <dependency>
          <groupId>commons-fileupload</groupId>
          <artifactId>commons-fileupload</artifactId>
          <version>1.3.3</version>
      </dependency>
        
  2.2 配置文件上传解析器(CommonsMultipartResolver)
      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
    </bean>

  2.3 表单提交方式为method="post" enctype="multipart/form-data"

前端上传页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <%@include file="/common/head.jsp" %>
</head>
<body>
<h1>书本图片上传</h1>
<form action="${ctx}/bookFile/upload" method="post" enctype="multipart/form-data">
    <label>书本Id</label><input type="text" name="bookId" value="${param.bookId}" readonly="readonly"/><br/>
    <label>书本图片</label><input type="file" name="bFile"/><br/>
    <input type="submit" value="上传图片"/>
</form>
</body>
</html>

  2.4 文件项用spring提供的MultipartFile进行接收
      BookFileVo
         bookId
         MultipartFile

  2.5 上传文件

      注:springmvc文件上传关键代码
      File targetFile = ....;
      MultipartFile mf = ....;
      String fileName = mf.getOriginalFilename(); 
      mf.transferTo(targetFile);

后台实现代码

在target目录下的ssm文件夹下创建upload文件夹储存上传的文件

    private static final String  DEAULT_PATH="/uploads/"; 
 
    /**
     * 文件上传
     * @return
     */
    @RequestMapping("/upload")
    public  String upload(MultipartFile bfile,HttpServletRequest request){
        try{
            //获取文件名
            String Filename = bfile.getOriginalFilename();
 
            //获取图片路径
            String path=DEAULT_PATH+Filename;
            //获取保存图片的绝地路径
            String filePath = transfor(path, request);
 
            //将上传的图片保存到指定位置(读流写流)
            bfile.transferTo(new File(filePath));
            
        }catch (Exception e){
            e.printStackTrace();
        }
        return "redirect:/book/queryBookPage";
    }
 
 
    /**
         * 将相对路径转为绝对路径
         * @param relativePath
         * @return
     */
    private String transfor(String relativePath, HttpServletRequest request){
        return  request.getServletContext().getRealPath(relativePath);
    }

  运行代码,去页面上传文件,检查本地文件夹target——>ssm——>upload文件中是否有照片

  2.6 下载文件
  @RequestMapping(value="/download")
public ResponseEntity<byte[]> download(@RequestParam String fileId){

   //先根据文件id查询对应图片信息

   //下载关键代码
   File file=new File(bookFile.getUrl());
   HttpHeaders headers = new HttpHeaders();//http头信息
   String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
   headers.setContentDispositionFormData("attachment", downloadFileName);
   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
   //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
   return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

}

文件后台下载代码

@RequestMapping(value="/download")
    public ResponseEntity<byte[]> download(@RequestParam String fileId, HttpServletRequest request){
 
        try{
            //先根据文件id查询对应图片信息
            BookFile bookFile = bookFileService.selectByPrimaryKey(fileId);
            //数据库中图片的相对路径转换成绝对路径
            String transfor = transfor(bookFile.getUrl(), request);
            //下载关键代码
            File file=new File(transfor);
            //http头信息
            HttpHeaders headers = new HttpHeaders();
            String downloadFileName = new String(bookFile.getRealName().getBytes("UTF-8"),"iso-8859-1");//设置编码
            headers.setContentDispositionFormData("attachment", downloadFileName);
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
            return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
 
    }

下载途径有两种

谷歌浏览器——》下载到本地下载文件夹

360——》可以选择下载路径

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值