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

    上传:

    Servlet2.5

    1 <form action="${pageContext.request.contextPath }/uploadServlet" method="POST" enctype="multipart/form-data">
    2         姓名:<input type="text" name="name"/> <br>
    3         年龄:<input type="text" name="age"/> <br>
    4         照片:<input type="file" name="photo"/> <br>
    5         <input type="submit" value="注册"/>
    6 </form>
      1 package com.lijie.servlets;
      2 
      3 import java.io.File;
      4 import java.io.FileOutputStream;
      5 import java.io.IOException;
      6 import java.io.InputStream;
      7 import java.io.OutputStream;
      8 import java.io.PrintWriter;
      9 import java.text.SimpleDateFormat;
     10 import java.util.Calendar;
     11 import java.util.Date;
     12 import java.util.Iterator;
     13 import java.util.List;
     14 
     15 import javax.servlet.ServletException;
     16 import javax.servlet.ServletInputStream;
     17 import javax.servlet.http.HttpServlet;
     18 import javax.servlet.http.HttpServletRequest;
     19 import javax.servlet.http.HttpServletResponse;
     20 
     21 import org.apache.commons.fileupload.FileItem;
     22 import org.apache.commons.fileupload.FileUploadException;
     23 import org.apache.commons.fileupload.disk.DiskFileItemFactory;
     24 import org.apache.commons.fileupload.servlet.ServletFileUpload;
     25 
     26 
     27 public class UploadServlet extends HttpServlet {
     28     private static final long serialVersionUID = 1L;
     29 
     30     
     31     protected void doPost(HttpServletRequest request, HttpServletResponse response)
     32             throws ServletException, IOException {
     33         
     34         /*ServletInputStream is = request.getInputStream();
     35         response.setContentType("text/html;charset=UTF-8");
     36         
     37         PrintWriter out = response.getWriter();
     38         int len = -1;
     39         byte[] buffer = new byte[1024];
     40         while((len = is.read(buffer))!=-1){
     41             String str = new String(buffer);
     42             out.println(str);
     43         }
     44         is.close();*/
     45         
     46         System.out.println("===========执行上传===========");
     47         //解析请求
     48         try {
     49             //判断请求类型
     50             boolean isMultipart = ServletFileUpload.isMultipartContent(request);
     51             if(!isMultipart){
     52                 throw new RuntimeException("当前请求不支持文件上传!");
     53             }
     54             //创建FileItem工厂
     55             DiskFileItemFactory factory = new DiskFileItemFactory();
     56             //设置使用临时文件的边界值(大于该值,上传文件会保存在临时文件中,小于等于该值,写入内存。单位:字节)
     57             //本例设置为1M(1M=1024KB 1KB=1024B)
     58             factory.setSizeThreshold(1024 * 1024 * 1);
     59             //设置临时文件(上传完毕后要删除temp文件夹下的文件)
     60             File tempFile = new File(this.getServletContext().getRealPath("/temp"));
     61             factory.setRepository(tempFile);
     62             
     63             //创建文件上传核心组件
     64             ServletFileUpload upload = new ServletFileUpload(factory);
     65             //防止文件名乱码
     66             upload.setHeaderEncoding("UTF-8");
     67             //限制单次上传的文件大小边界值
     68             upload.setFileSizeMax(1024*1024*2);
     69             //限制多文件上传时的大小总和(这里是单文件,所有不起作用)
     70             upload.setSizeMax(1024*1024*5);
     71             //解析请求获取所有的Item
     72             List<FileItem> items = upload.parseRequest(request);
     73             //遍历Item
     74             Iterator<FileItem> iter = items.iterator();
     75             while (iter.hasNext()) {
     76                 FileItem item = iter.next();
     77                 if (item.isFormField()) {
     78                     //普通表单项
     79                     String fieldName = item.getFieldName();
     80                     String fieldValue = item.getString("UTF-8");
     81                     System.out.println(fieldName+" = "+fieldValue);
     82                 } else {
     83                     //文件上传表单项
     84                     String fileName = item.getName();
     85                     //防止上传同名文件
     86                     fileName = System.currentTimeMillis() + fileName;
     87                     //输入流
     88                     InputStream is = item.getInputStream();
     89                     String path = this.getServletContext().getRealPath("/images");
     90                     
     91                     
     92                     //由于windows系统一个文件夹下最多有65535个文件
     93                     //所有对images文件夹下再进行分文件夹进行存储上传的文件
     94                     //1.按照yyyyMMdd的日期存放
     95                     /*Date now = new Date();
     96                     SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
     97                     String nowTime = format.format(now);
     98                     path =  path + "/" + nowTime;
     99                     System.out.println("文件在服务器地址:" + path);
    100                     File dirFile = new File(path);
    101                     if(!dirFile.exists()){
    102                         dirFile.mkdir();
    103                     }*/
    104                     //2.按照年月日的格式分多级目录存放
    105                     Calendar now = Calendar.getInstance();
    106                     int year = now.get(Calendar.YEAR);
    107                     int month = now.get(Calendar.MONTH) + 1;
    108                     int day = now.get(Calendar.DAY_OF_MONTH);
    109                     path =  path + "/" + year + "/" + month + "/" + day;
    110                     File dirFile = new File(path);
    111                     if(!dirFile.exists()){
    112                         dirFile.mkdirs();
    113                     }
    114                     //输出流
    115                     File file = new File(path ,fileName);
    116                     OutputStream os = new FileOutputStream(file);
    117                     int len = -1;
    118                     byte[] buffer = new byte[1024];
    119                     while((len=is.read(buffer)) != -1){
    120                         os.write(buffer,0, len);
    121                     }
    122                     os.flush();
    123                     os.close();
    124                     is.close();
    125                     //删除临时文件夹的文件
    126                     item.delete();
    127                 }
    128             }
    129             System.out.println("===========上传成功===========");
    130         } catch (FileUploadException e) {
    131             // TODO Auto-generated catch block
    132             e.printStackTrace();
    133         }
    134     }
    135 }

    Servlet3.0

    1 <form action="${pageContext.request.contextPath }/uploadServlet" method="POST" enctype="multipart/form-data">
    2         文件:<input type="file" name="file"><br>
    3         <input type="submit" value="上传">
    4     </form>
     1 package com.lijie.servlet;
     2 
     3 import java.io.IOException;
     4 import javax.servlet.ServletException;
     5 import javax.servlet.annotation.MultipartConfig;
     6 import javax.servlet.annotation.WebServlet;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 import javax.servlet.http.Part;
    11 
    12 @WebServlet("/uploadServlet")
    13 @MultipartConfig
    14 public class UploadServlet extends HttpServlet {
    15     
    16     protected void doPost(HttpServletRequest request, HttpServletResponse response)
    17             throws ServletException, IOException {
    18         
    19         String path = this.getServletContext().getRealPath("/images");
    20         Part part = request.getPart("file");
    21         
    22         String header = part.getHeader("Content-Disposition");
    23         int indexOf = header.lastIndexOf("=");
    24         String fileName = header.substring(indexOf+2, header.length()-1);
    25         part.write(path+"/"+fileName);
    26     }
    27 
    28 }

    下载:

    1 <a href="${pageContext.request.contextPath }/downloadServlet">跑车</a> <br>
     1 package com.lijie.servlets;
     2 
     3 import java.io.IOException;
     4 import java.io.InputStream;
     5 
     6 import javax.servlet.ServletException;
     7 import javax.servlet.ServletOutputStream;
     8 import javax.servlet.http.HttpServlet;
     9 import javax.servlet.http.HttpServletRequest;
    10 import javax.servlet.http.HttpServletResponse;
    11 
    12 public class DownloadServlet extends HttpServlet {
    13     protected void doGet(HttpServletRequest request, HttpServletResponse response)
    14             throws ServletException, IOException {
    15         
    16         String fileName = "超跑.jpg";
    17         
    18         // 打散:按当前的字符编码进行打散
    19         byte[] bytes = fileName.getBytes("UTF-8");
    20         // 组装:按目标字符编码进行组装
    21         fileName = new String(bytes, "ISO8859-1");
    22         
    23         // 修改响应的头部属性content-disposition值为attachment
    24         response.setHeader("content-disposition", "attachment;filename=" + fileName);
    25         
    26         // 获取连接服务端资源文件的输入流
    27         InputStream is = this.getServletContext().getResourceAsStream("/resources/aaa.jpg");
    28         // 获取输出流 
    29         ServletOutputStream os = response.getOutputStream();
    30         // 将输入流中的数据写入到输出流中
    31         int len = -1;
    32         byte[] buf = new byte[1024];
    33         while((len = is.read(buf)) != -1) {
    34             os.write(buf, 0, len);
    35         }        
    36         // 关闭流
    37         os.close();
    38         is.close();
    39     }
    40 }
  • 相关阅读:
    MySQL 视图的作用
    基类一定要设置虚析构函数,否则会内存泄露
    Delphi ISO,包括D2010DXE6比较全面的测评(绝美PDF)
    一些最重要的PHP数组函数
    没有虚函数情况下的函数覆盖(以原始指针的类型为准)
    使用Mono.Cecil辅助ASP.NET MVC使用dynamic类型Model
    持续集成(CI) TeamCity实战概览
    对.Net状态保持机制和并发问题的思考
    Windows Communication Foundation 概述
    Welcome to HDU Online Judge System
  • 原文地址:https://www.cnblogs.com/lijie0609/p/12082867.html
Copyright © 2011-2022 走看看