zoukankan      html  css  js  c++  java
  • 文件上传与下载

    对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用Servlet获取上传文件的输入流然后再解析里面的请求参数是比较麻烦,所以一般选择采用apache的开源工具common-fileupload这个文件上传组件。common-fileupload是依赖于common-io这个包的,所以还需要下载这个包。

    文件上传流程:

    1、jsp页面上传文件

    2、后台获取文件流(原理都是一样的,实现方式有所不同。

    sevelet一般用ServletFileUpload从HttpServletRequest获取;

    struts2会自动将文件流封装为File对象;springmvc则是MultipartFile)

    3、获取输出流,在相应目录生成文件

    文件上传页面index.jsp代码

     1 <%@ page language="java" contentType="text/html; charset=UTF-8"   
     2     pageEncoding="UTF-8"%>     
     3 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
     4 
     5 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">    
     6 <html>   
     7 <head>    
     8 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">    
     9 <title>Insert title here</title>  
    10 </head>  
    11 <body>    
    12     <h1>test file upload</h1>    
    13     <form action="fileUpload" method="post" enctype="multipart/form-data">  
    14         <input type="hidden" name="method" value="upload"/>  
    15         <input type="file" name="file"/>  
    16         <input type="submit" value="upload"/> 
    17     </form>
    18 </body>    
    19 </html>
    View Code

    文件处理类代码

      1 package com.updown.controller;
      2 
      3 import java.io.BufferedInputStream;
      4 import java.io.BufferedOutputStream;
      5 import java.io.File;
      6 import java.io.FileInputStream;
      7 import java.io.InputStream;
      8 import java.io.OutputStream;
      9 import java.text.SimpleDateFormat;
     10 import java.util.Date;
     11 import java.util.List;
     12 import java.util.UUID;
     13 
     14 import javax.annotation.Resource;
     15 import javax.servlet.http.HttpServletRequest;
     16 import javax.servlet.http.HttpServletResponse;
     17 import org.springframework.stereotype.Controller;
     18 import org.springframework.web.bind.annotation.RequestMapping;
     19 import org.springframework.web.multipart.MultipartFile;
     20 import org.springframework.web.multipart.MultipartHttpServletRequest;
     21 
     22 import com.updown.entity.Content;
     23 import com.updown.service.ContentService;
     24 
     25 @Controller   
     26 public class FileOperateController{
     27       
     28     /** 
     29      * 上传文件
     30      * @param request 
     31      * @param model 
     32      * @return 
     33      */ 
     34     @Resource(name = "contentService")
     35      private ContentService contentService;
     36     @RequestMapping  
     37     public String toUpload(){  
     38         return "index";  
     39     } 
     40     
     41     @RequestMapping( value="fileUpload")
     42     public String upload(HttpServletRequest request) throws Exception{  
     43         
     44         MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;     
     45         SimpleDateFormat dateformat = new SimpleDateFormat("yyyy/MM/dd/HH");     
     46         //构建保存的目录   
     47         String fileRelativePath = "/files"+ dateformat.format(new Date());     
     48         //得到保存目录的真实路径  
     49         String fileRealPath = request.getSession().getServletContext().getRealPath(fileRelativePath);     
     50         //根据真实路径创建目录  
     51         File saveFile = new File(fileRealPath);     
     52         if(!saveFile.exists())     
     53             saveFile.mkdirs();  //mkdirs()返回当且仅当创建的目录,以及所有必需的父目录         
     54         //页面控件的文件流,返回此请求中上传文件的内容加上说明,或者如果它不存在则返回空
     55         MultipartFile multipartFile = multipartRequest.getFile("file");      
     56         //获取文件的后缀,getOriginalFilename返回到原来的文件名在客户端的文件系统 
     57         String suffix = multipartFile.getOriginalFilename().substring  
     58                         (multipartFile.getOriginalFilename().lastIndexOf("."));     
     59         //文件白名单
     60         String[] fileType={"gif","jpg","jpeg","png","bmp","doc","docx","pdf","xls","xlsx","txt","zip","rar"};
     61         //循环查找字符串数组中的每个字符串中是否包含所有查找的内容
     62         for(int i=0;i<fileType.length;i++){
     63                if(fileType[i].indexOf(suffix.substring(1))!=-1){
     64         
     65         String uuid = UUID.randomUUID().toString();
     66         String fileName = multipartFile.getOriginalFilename();  
     67         //拼成完整的文件保存路径加文件   
     68         String fileAbsolutePath = fileRealPath + File.separator   + fileName;                
     69         File file = new File(fileAbsolutePath); 
     70         
     71             multipartFile.transferTo(file);  
     72      
     73             Content content=new Content();
     74             content.setPath(fileRelativePath);
     75             content.setDate(dateformat.format(new Date())+ uuid );
     76             content.setTitle(fileName);
     77         //数据库操作    
     78         int up_result=contentService.addContent(content);
     79         List<Content> list=contentService.listAllDepartment();
     80         request.setAttribute("list",list);
     81         }      
     82                }
     83         return "/success";
     84     }
     85     
     86     /** 
     87      * 下载文件
     88      * @param request 
     89      * @param response 
     90      * @return 
     91      */ 
     92     @RequestMapping(value = "download")  
     93     public void download(HttpServletRequest request,HttpServletResponse response)throws Exception{
     94 
     95         String title=request.getParameter("title");
     96         Content content=contentService.getContentByTitle(title);
     97         String fileSqlSavePath = content.getPath(); 
     98         String fileServerPath=request.getSession().getServletContext().getRealPath(fileSqlSavePath);
     99         String fileAbsolutePath=fileServerPath+"\"+title;
    100         File file = new File(fileAbsolutePath);
    101         // 取得文件的后缀名
    102         String suffix = title.substring(title.lastIndexOf("."));
    103         // 以流的形式下载文件
    104         InputStream fis = new BufferedInputStream(new FileInputStream(fileAbsolutePath));
    105         //public int available() throws IOException{}返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取的字节数。返回一个整数值
    106         byte[] buffer = new byte[fis.available()];
    107         //这个方法从输入流读取buffer.length长度的字节。返回读取的字节数。如果是文件结尾则返回-1
    108         fis.read(buffer);
    109         fis.close();
    110         // 清空response
    111         response.reset();
    112         // 设置response的Header
    113         response.addHeader("Content-Disposition", "attachment;filename=" + new String(title.getBytes("gb2312"),"iso8859-1"));
    114         response.addHeader("Content-Length", "" + file.length());
    115         OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
    116         response.setContentType("application/octet-stream");
    117         toClient.write(buffer);
    118         toClient.flush();
    119         toClient.close();
    120     }
    121 }
    View Code
  • 相关阅读:
    第二次作业循环语句
    c语言01次作业分支,顺序结构
    PAT 1027. Colors in Mars
    PAT 1026 Table Tennis
    PAT 1035 Password
    PAT 1038. Recover the Smallest Number
    PAT 1028 List Sorting (25)
    PAT 1041 Be Unique (20)
    PAT 1025 PAT Ranking
    1037. Magic Coupon
  • 原文地址:https://www.cnblogs.com/imax0316/p/4886465.html
Copyright © 2011-2022 走看看