码迷,mamicode.com
首页 > Web开发 > 详细

文件上传与下载

时间:2019-12-23 13:08:58      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:tps   boolean   成功   throw   xtend   设置   encoding   多文件上传   大小   

上传:

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 }

下载:

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 }

文件上传与下载

标签:tps   boolean   成功   throw   xtend   设置   encoding   多文件上传   大小   

原文地址:https://www.cnblogs.com/lijie0609/p/12082867.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!