springMVC文件上传和下载

文件上传和下载

教室版

一、上传

Web端需要满足的条件

1.input里的type为file
2.提交的方式为post
3.form表单的属性必须有enctype且设置为multipart/form-data
<form id="documentForm" name="documentForm" action="${pageContext.request.contextPath}/document/addDocument" enctype="multipart/form-data" method="post">
                   <!-- 隐藏表单,flag表示添加标记 -->
         <input type="hidden" name="flag" value="2">
 <table width="100%" border="0" cellpadding="0" cellspacing="10" class="main_tab">
                   
    <tr><td class="font3 fftd">
              
                
                文档标题:<input type="text" name="title" size="30" id="title"/></td>
    </tr>
   <tr><td class="main_tdbor"></td></tr>
   
   
   <tr><td class="font3 fftd">文档描述:<br/>
      <textarea name="remark" cols="88" rows="11" id="content"></textarea>
   </td></tr>
   <tr><td class="main_tdbor"></td></tr>
   
      <tr><td class="font3 fftd">文档:<br/>
      <input type="file" name="file" id="file"  size="30"/>
   </td></tr>
   <tr><td class="main_tdbor"></td></tr>
   
                 
   
   <tr><td class="font3 fftd">
         <input type="submit" id="btn" value="上传">
         <input type="reset" value="重置">
   </td></tr>
   <tr><td class="main_tdbor"></td></tr>


 </table>
 </form>

后台接受上传的文档满足的条件

/*
 * 后台接受上传的文档满足的条件
 * 1.接受类型——MultipartFile file
 * 2.文件上传所需要的依赖:commons-fileupload
 * 3.文件上传所需要的解析器——在spring-mvc配置文件中注册MultipartFile解析器
 * */
public String addDocument(Model model, Document document, HttpSession session, HttpServletRequest request) throws IOException {
    //获取当前登录的用户
    User login_user = (User) session.getAttribute("login_user");
    document.setUser(login_user);

    // 文件保存的路径——磁盘或者项目的路径下
    String dirPath = "d:/upload/";
    // String dirPath = session.getServletContext().getRealPath("/files") + "/";
    File filePath = new File(dirPath);
    //路径不存在则先创建路径
    if (!filePath.exists()) {
        filePath.mkdirs();
    }
    // 获取上传文件的文件名称,包含后缀名,另外加上一个随机生成的ID(UUID.randomUUID()),防止名字重复导致覆盖
    // 还可以使用System.currentTimeMillis()获取当前系统的时间加到文件名中
    String filename = System.currentTimeMillis() + "--" + document.getFile().getOriginalFilename();
    File file = new File(dirPath + filename);
    // 将获得的文件转存的创建的位置
    document.getFile().transferTo(file);
    // 设置文件名
    document.setFilename(filename);

    // 数据库插入
    int row = documentService.addDocument(document);
    if (row > 0) {
        int recordCount = documentService.findDocumentCount(null);
        PageModel pageModel = new PageModel();
        pageModel.setRecordCount(recordCount);
        int totalSize = pageModel.getTotalSize();
        return "redirect:/document/findDocument?pageIndex=" + totalSize;
    }
    model.addAttribute("fail", "文档添加失败");
    return "/fail.jsp";
}

二、文档的下载

// downLoad document
@RequestMapping("/downLoad")
/*
 * 这里返回值是响应实体,其中的值是字节流
 * */
public ResponseEntity<Object> downLoad(int id, HttpServletRequest request) throws IOException {
    String dirPath = "d:/upload/";
    Document targetDocument = documentService.findDocumentById(id);
    String filename = targetDocument.getFilename();
    // 获取下载的目标文件
    File file = new File(dirPath, filename);

    if (file.exists()){
        // 为解决不同浏览器中文乱码问题(IE、火狐、谷歌)
        filename = processFileName(request, filename);
        // 设置响应头的响应内容类型
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);// 响应流文件
        headers.setContentDispositionFormData("attachment", filename);// 作为附件响应回去
        return new ResponseEntity<Object>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
    }else {
        String error = "下载的文档不存在";
        // 设置响应头的响应内容是HTML
        HttpHeaders headers = new HttpHeaders();
        MediaType mediaType = new MediaType("text","html", Charset.forName("utf-8"));
        headers.setContentType(mediaType);
        return new ResponseEntity<Object>(error, headers, HttpStatus.OK);
    }
}

// 不同浏览器中文乱码问题(IE、火狐、谷歌)
public String processFileName(HttpServletRequest request, String fileNames) {
    String codedFilename = null;
    try {
        String agent = request.getHeader("USER-AGENT");
        if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {
            // IE
            String name = java.net.URLEncoder.encode(fileNames, "UTF8");
            codedFilename = name;
        } else if (null != agent && -1 != agent.indexOf("Mozilla")) {
            // chrome、火狐
            codedFilename = new String(fileNames.getBytes("UTF-8"), "iso-8859-1");
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return codedFilename;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值