一文件的上传

实体类

  1. CODE上查看代码片派生到我的代码片
  2. import java.sql.Timestamp;
  3.  
  4. /**
  5. *
  6. * @Decription 文件上传实体类
  7. * @author 刘楠
  8. *
  9. * @time2016-1-31上午11:17:46
  10. */
  11. public class Upfile {
  12.  
  13. private String id;// ID主键 使用uuid随机生成
  14. private String uuidname; // UUID名称
  15. private String filename;//文件名称
  16. private String savepath; // 保存路径
  17. private Timestamp uploadtime; // 上传时间
  18. private String description;// 文件描述
  19. private String username; // 用户名
  20.  
  21. public Upfile() {
  22. super();
  23. }
  24.  
  25. public Upfile(String id, String uuidname, String filename, String savepath,
  26. Timestamp uploadtime, String description, String username) {
  27. super();
  28. this.id = id;
  29. this.uuidname = uuidname;
  30. this.filename = filename;
  31. this.savepath = savepath;
  32. this.uploadtime = uploadtime;
  33. this.description = description;
  34. this.username = username;
  35. }
  36.  
  37. public String getDescription() {
  38. return description;
  39. }
  40.  
  41. public String getFilename() {
  42. return filename;
  43. }
  44.  
  45. public String getId() {
  46. return id;
  47. }
  48.  
  49. public String getSavepath() {
  50. return savepath;
  51. }
  52.  
  53. public Timestamp getUploadtime() {
  54. return uploadtime;
  55. }
  56.  
  57. public String getUsername() {
  58. return username;
  59. }
  60.  
  61. public String getUuidname() {
  62. return uuidname;
  63. }
  64.  
  65. public void setDescription(String description) {
  66. this.description = description;
  67. }
  68.  
  69. public void setFilename(String filename) {
  70. this.filename = filename;
  71. }
  72.  
  73. public void setId(String id) {
  74. this.id = id;
  75. }
  76.  
  77. public void setSavepath(String savepath) {
  78. this.savepath = savepath;
  79. }
  80.  
  81. public void setUploadtime(Timestamp uploadtime) {
  82. this.uploadtime = uploadtime;
  83. }
  84.  
  85. public void setUsername(String username) {
  86. this.username = username;
  87. }
  88.  
  89. public void setUuidname(String uuidname) {
  90. this.uuidname = uuidname;
  91. }
  92.  
  93. }

页面

 
  1. CODE上查看代码片派生到我的代码片
  2. <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. %>
  7.  
  8. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  9. <html>
  10. <head>
  11. <base href="<%=basePath%>">
  12.  
  13. <title>My JSP 'upload.jsp' starting page</title>
  14.  
  15. <meta http-equiv="pragma" content="no-cache">
  16. <meta http-equiv="cache-control" content="no-cache">
  17. <meta http-equiv="expires" content="0">
  18. <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
  19. <meta http-equiv="description" content="This is my page">
  20. <!--
  21. <link rel="stylesheet" type="text/css" href="styles.css">
  22. -->
  23.  
  24. </head>
  25.  
  26. <body>
  27. <h1>文件上传</h1>
  28. <form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data">
  29. <table>
  30. <tr>
  31. <td> 上传用户名:</td>
  32. <td><input type="text" name="username"/></td>
  33. </tr>
  34. <tr>
  35. <td> 上传文件:</td>
  36. <td><input type="file" name="file"/></td>
  37. </tr>
  38. <tr>
  39. <td> 描述:</td>
  40. <td><textarea rows="5" cols="50" name="description"></textarea></td>
  41. </tr>
  42. <tr>
  43. <td><input type="submit" value="上传开始"/></td>
  44. </tr>
  45. </table>
  46. </form>
  47. <div>${msg }</div>
  48. <a href="${pageContext.request.contextPath }/index.jsp">返回主页</a>
  49. </body>
  50. </html>

Servlet

  1. CODE上查看代码片派生到我的代码片
  2. import java.io.IOException;
  3.  
  4. import javax.servlet.ServletException;
  5. import javax.servlet.http.HttpServlet;
  6. import javax.servlet.http.HttpServletRequest;
  7. import javax.servlet.http.HttpServletResponse;
  8.  
  9. import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
  10. import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
  11. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  12.  
  13. import com.itheima.domain.Upfile;
  14. import com.itheima.exception.MyException;
  15. import com.itheima.service.UpfileService;
  16. import com.itheima.service.impl.UpfileServiceImpl;
  17. import com.itheima.untils.WebUntil;
  18.  
  19. public class UploadFileServlet extends HttpServlet {
  20.  
  21. public void doGet(HttpServletRequest request, HttpServletResponse response)
  22. throws ServletException, IOException {
  23.  
  24. doPost(request, response);
  25. }
  26.  
  27. public void doPost(HttpServletRequest request, HttpServletResponse response)
  28. throws ServletException, IOException {
  29. //判断表单是不是多个部分组成的
  30. if(!ServletFileUpload.isMultipartContent(request)){
  31.  
  32. request.setAttribute("msg", "表单个设置错误,请检查enctype属性是是否设置正确");
  33. request.getRequestDispatcher("/upload.jsp").forward(request, response);
  34. return ;
  35. }
  36. //是多部分组成的就获取并遍历返回一个文件上传对象,包含上传的所有信息
  37. try {
  38. Upfile upfile=WebUntil.upload(request);
  39.  
  40. UpfileService upfileService=new UpfileServiceImpl();
  41. boolean flag=upfileService.add(upfile);
  42.  
  43. if(flag){
  44. request.setAttribute("msg", "上传成功");
  45. request.getRequestDispatcher("/upload.jsp").forward(request, response);
  46. return ;
  47. }else{
  48. request.setAttribute("msg", "上传失败,请重试");
  49. request.getRequestDispatcher("/upload.jsp").forward(request, response);
  50. return ;
  51. }
  52.  
  53. }catch (FileSizeLimitExceededException e) {
  54. e.printStackTrace();
  55. request.setAttribute("msg", "单个文件大小 ,超过最大限制");
  56. request.getRequestDispatcher("/upload.jsp").forward(request, response);
  57. return ;
  58. } catch (SizeLimitExceededException e) {
  59. e.printStackTrace();
  60. request.setAttribute("msg", "总文件大小 ,超过最大限制");
  61. request.getRequestDispatcher("/upload.jsp").forward(request, response);
  62. return ;
  63. }
  64.  
  65. }
  66.  
  67. }

工具类

  1. CODE上查看代码片派生到我的代码片
  2. import java.io.File;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileOutputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.io.UnsupportedEncodingException;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.UUID;
  12.  
  13. import javax.servlet.http.HttpServletRequest;
  14.  
  15. import org.apache.commons.fileupload.FileItem;
  16. import org.apache.commons.fileupload.FileUploadBase;
  17. import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;
  18. import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
  19. import org.apache.commons.fileupload.FileUploadException;
  20. import org.apache.commons.fileupload.ProgressListener;
  21. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  22. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  23.  
  24. import com.itheima.domain.Upfile;
  25. import com.itheima.exception.MyException;
  26. /**
  27. * 文件上传工具类
  28. * @Decription TODO
  29. * @author 刘楠
  30. *
  31. * @time2016-1-31下午12:56:02
  32. */
  33. public class WebUntil {
  34.  
  35. /**
  36. * 文件上传的方法
  37. * @param request 请求参数传入
  38. * @return 返回一个Upfile对象
  39. * @throws FileSizeLimitExceededException
  40. * @throws SizeLimitExceededException
  41. * @throws IOException
  42. */
  43. public static Upfile upload(HttpServletRequest request) throws FileSizeLimitExceededException, SizeLimitExceededException {
  44. Upfile upfile=new Upfile();
  45. ArrayList<String> fileList=initList();
  46. try {
  47. //获取磁盘文件对象工厂
  48. DiskFileItemFactory factory=new DiskFileItemFactory();
  49. String tmp=request.getSession().getServletContext().getRealPath("/tmp");
  50. System.out.println(tmp);
  51. //初始化工厂
  52. setFactory(factory,tmp);
  53. //获取文件上传解析器
  54. ServletFileUpload upload=new ServletFileUpload(factory);
  55. //初始化解析器
  56. setUpload(upload);
  57. //获取文件列表集合
  58. List<FileItem> list = upload.parseRequest(request);
  59. //遍历
  60. for (FileItem items : list) {
  61. //判断 是不是普通表单个对象
  62. if(items.isFormField()){
  63. //获取上传表单的name
  64. String fieldName=items.getFieldName();
  65. //value
  66. String fieldValue=items.getString("UTF-8");
  67. //判断
  68. if("username".equals(fieldName)){
  69. //设置
  70.  
  71. upfile.setUsername(fieldValue);
  72. }else if("description".equals(fieldName)){
  73. //设置属性
  74. upfile.setDescription(fieldValue);
  75. }
  76.  
  77. }else{
  78. //是文件就准备上传
  79. //获取文件名
  80. String filename=items.getName();
  81. //处理因为浏览器不同而导致的 获得 的 文件名的 差异
  82. int index=filename.lastIndexOf("\\");
  83. if(index!=-1){
  84. filename=filename.substring(index+1);
  85. }
  86.  
  87. //生成随机的文件名
  88.  
  89. String uuidname=generateFilename(filename);
  90.  
  91. //获取上传的文件路径
  92. String savepath=request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
  93. //获取请求对象中的输入流
  94. InputStream in = items.getInputStream();
  95. //将文件打散存放在不同的路径,求出路径
  96. savepath=generateRandomDir(savepath,uuidname);
  97.  
  98. //复制文件
  99.  
  100. uploadFile(in,savepath,uuidname);
  101. String id=UUID.randomUUID().toString();
  102. upfile.setId(id);
  103. upfile.setSavepath(savepath);
  104. upfile.setUuidname(uuidname);
  105. upfile.setFilename(filename);
  106. //清除缓存
  107. items.delete();
  108. }
  109.  
  110. }
  111.  
  112. }catch ( FileUploadBase.FileSizeLimitExceededException e) {
  113. //抛出出异常
  114. throw e;
  115. } catch (FileUploadBase.SizeLimitExceededException e) {
  116. //抛出出异常
  117. throw e;
  118. }catch (FileUploadException e) {
  119. e.printStackTrace();
  120. } catch (UnsupportedEncodingException e) {
  121. e.printStackTrace();
  122. } catch (IOException e) {
  123. e.printStackTrace();
  124. } catch (Exception e) {
  125. e.printStackTrace();
  126. }
  127.  
  128. return upfile;
  129. }
  130.  
  131. /**
  132. * 初始化文件列表
  133. * @return
  134. */
  135. private static ArrayList<String> initList() {
  136. ArrayList<String> list=new ArrayList<String>();
  137. list.add(".jpg");
  138. list.add(".rar");
  139. list.add(".txt");
  140. list.add(".png");
  141.  
  142. return list;
  143. }
  144.  
  145. /**
  146. * 复制文件
  147. * @param in items中的输入流
  148. * @param savepath 保存路径
  149. * @param uuidname 文件名
  150. */
  151. private static void uploadFile(InputStream in, String savepath,
  152. String uuidname) {
  153. //获取文件
  154. File file=new File(savepath, uuidname);
  155. OutputStream out = null;
  156. try {
  157. int len=0;
  158. byte [] buf=new byte[1024];
  159. //获取输出流
  160. out = new FileOutputStream(file);
  161. while((len=in.read(buf))!=-1){
  162. out.write(buf, 0, len);
  163. }
  164.  
  165. } catch (FileNotFoundException e) {
  166. e.printStackTrace();
  167. } catch (IOException e) {
  168. e.printStackTrace();
  169. }finally{
  170. try {
  171. in.close();
  172. } catch (IOException e) {
  173. e.printStackTrace();
  174. }
  175. try {
  176. out.close();
  177. } catch (IOException e) {
  178. e.printStackTrace();
  179. }
  180. }
  181.  
  182. }
  183.  
  184. /**
  185. * 生成随机的存放路径
  186. * @param savepath 保存路径
  187. * @param uuidname 生成的uuid名称
  188. * @return
  189. * 使用hashcode完成
  190. */
  191. private static String generateRandomDir(String savepath, String uuidname) {
  192. //转化为hashcode
  193. System.out.println("上传路径"+savepath);
  194. System.out.println("UUIDNAME"+uuidname);
  195. int hashcode=uuidname.hashCode();
  196. //容器
  197. StringBuilder sb=new StringBuilder();
  198. while(hashcode>0){
  199. //与上15
  200. int tmp=hashcode&0xf;
  201.  
  202. sb.append("/");
  203. sb.append(tmp+"");
  204. hashcode=hashcode>>4;
  205. }
  206. //拼接新的路径
  207. String path=savepath+sb.toString();
  208. System.out.println("path"+path);
  209. File file=new File(path);
  210. //判断路径存不存在
  211. if(!file.exists()){
  212. //不存在就创建
  213. file.mkdirs();
  214. }
  215.  
  216. //返回保存路径
  217. return path;
  218. }
  219.  
  220. /**
  221. * 生成新的文件名
  222. * @param uuidname 随机的ID名字
  223. * @param filename 原来的名
  224. * @return
  225. */
  226. private static String generateFilename( String filename) {
  227. String uuidname=UUID.randomUUID().toString();
  228. return uuidname.replace("-", "").toString()+"_"+filename;
  229. }
  230.  
  231. /**
  232. * 初始化解析器
  233. * @param upload
  234. */
  235. private static void setUpload(ServletFileUpload upload) {
  236. // 设置 字符编码
  237. upload.setHeaderEncoding("utf-8");
  238. //设置文件大小
  239. upload.setFileSizeMax(1024*1024*20);
  240. //设置总文件大小
  241. upload.setSizeMax(1024*1024*50);
  242. //设置进度监听器
  243. upload.setProgressListener(new ProgressListener() {
  244.  
  245. public void update(long pBytesRead, long pContentLength, int pItems) {
  246. System.out.println("已经读取: "+pBytesRead+",总共有: "+pContentLength+", 第"+pItems+"个");
  247.  
  248. }
  249. });
  250.  
  251. }
  252.  
  253. /**
  254. * 工厂初始化方法
  255. * @param factory
  256. * @param tmp 缓冲目录
  257. */
  258. private static void setFactory(DiskFileItemFactory factory, String tmp) {
  259. /// 配置初始化值缓冲区
  260. factory.setSizeThreshold(1024*1024);
  261. File file=new File(tmp);
  262. //设置缓冲目录
  263. factory.setRepository(file);
  264.  
  265. }
  266.  
  267. }

二文件下载

Servlet

  1. public class DownupfileServlet extends HttpServlet {
  2.  
  3. public void doGet(HttpServletRequest request, HttpServletResponse response)
  4. throws ServletException, IOException {
  5.  
  6. doPost(request, response);
  7. }
  8.  
  9. public void doPost(HttpServletRequest request, HttpServletResponse response)
  10. throws ServletException, IOException {
  11. //获取ID
  12. String id=request.getParameter("id");
  13. //业务层的接口
  14. UpfileService upfileService=new UpfileServiceImpl();
  15. //根据ID查找这个对象
  16. Upfile upfile=upfileService.findUpfileById(id);
  17. if(upfile==null){
  18. return;
  19. }
  20. //获取文件的真实名称
  21. String filename=upfile.getFilename();
  22. //如果文件名中有中文,需要转码,不然就下载时没有文件名
  23. filename=URLEncoder.encode(filename, "utf-8");
  24. //更改过的名称
  25. String uuidname=upfile.getUuidname();
  26. //保存路径
  27. String savepath=upfile.getSavepath();
  28. File file=new File(savepath,uuidname);
  29. //判断文件 是否存在
  30. if(!file.exists()){
  31. request.setAttribute("msg", "下载 的文件过期了");
  32. request.getRequestDispatcher("/index").forward(request, response);
  33. return;
  34. }
  35. //设置文件下载响应头信息
  36. response.setHeader("Content-disposition", "attachement;filename="+filename);
  37. //使用IO流输出
  38. InputStream in = new FileInputStream(file);
  39. ServletOutputStream out = response.getOutputStream();
  40. int len=0;
  41. byte [] buf=new byte[1024];
  42. while((len=in.read(buf))!=-1){
  43. out.write(buf, 0, len);
  44. }
  45. in.close();
  46.  
  47. }
  48.  
  49. }
 

数据库

  1. create database upload_download_exercise;
  2. use upload_download_exercise;
  3. create table upfiles(
  4. id varchar(100), //使用UUID生成
  5. uuidname varchar(255),//uuid加上原来的文件名
  6. filename varchar(100),//真实文件名
  7. savepath varchar(255),//保存路径
  8. uploadtime timestamp,//上传时间
  9. description varchar(255),//描述
  10. username varchar(10) 上传人
  11. );

JAVA-使用commos-fileupload实现文件上传与下载的更多相关文章

  1. java框架篇---struts之文件上传和下载

    Struts2文件上传 Struts 2框架提供了内置支持处理文件上传使用基于HTML表单的文件上传.上传一个文件时,它通常会被存储在一个临时目录中,他们应该由Action类进行处理或移动到一个永久的 ...

  2. java web学习总结(二十四) -------------------Servlet文件上传和下载的实现

    在Web应用系统开发中,文件上传和下载功能是非常常用的功能,今天来讲一下JavaWeb中的文件上传和下载功能的实现. 对于文件上传,浏览器在上传的过程中是将文件以流的形式提交到服务器端的,如果直接使用 ...

  3. java文件上传和下载

    简介 文件上传和下载是java web中常见的操作,文件上传主要是将文件通过IO流传放到服务器的某一个特定的文件夹下,而文件下载则是与文件上传相反,将文件从服务器的特定的文件夹下的文件通过IO流下载到 ...

  4. java代码实现ftp服务器的文件上传和下载

    java代码实现文件上传到ftp服务器: 1:ftp服务器安装: 2:ftp服务器的配置: 启动成功: 2:客户端:代码实现文件的上传与下载: 1:依赖jar包: 2:sftpTools   工具类: ...

  5. Java Web(十一) 文件上传与下载

    文件上传 上传的准备工作 表单method必须为post 提供file组件 设置form标签的enctype属性为multipart/form-data,如果没有设置enctype属性,浏览器是无法将 ...

  6. 【Java】JavaWeb文件上传和下载

    文件上传和下载在web应用中非常普遍,要在jsp环境中实现文件上传功能是非常容易的,因为网上有许多用java开发的文件上传组件,本文以commons-fileupload组件为例,为jsp应用添加文件 ...

  7. Java精选笔记_文件上传与下载

    文件上传与下载 如何实现文件上传 在Web应用中,由于大多数文件的上传都是通过表单的形式提交给服务器的,因此,要想在程序中实现文件上传的功能,首先得创建一个用于提交上传文件的表单页面. 为了使Serv ...

  8. java的文件上传和下载 抄袭别人的.在底部有说明.

    =======后续 这里采用的是输出流的方式,我电脑装的是windows系统,测试没有问题,但是当把项目放到Linux系统上跑时,就会出现保存位置错误的情况, 指定的路径就会被当做文件名的一部分保存了 ...

  9. Java文件上传与下载

    文件上传与下载可谓上网中的常见现象.apache为我们准备了用于文件上传与下载的两个jar包(commons-fileupload-1.2.1.jar,commons-io-1.4.jar).我们在w ...

  10. Java 文件上传与下载、email

    1. 文件上传与下载 1.1 文件上传 文件上传,要点: 前台: 1. 提交方式:post 2. 表单中有文件上传的表单项: <input type="file" /> ...

随机推荐

  1. 【原创】MYSQL++源码剖析——前言与目录

    终于完成了! 从第一次想写到现在真的写好大概花了我3个月时间.原来一直读人家的系列文章,总感慨作者的用心良苦和无私奉献,自己在心里总是会觉得有那么些冲动也来写一个. 最开始的麻烦是犹豫该选哪个主题.其 ...

  2. Java知多少(108)数据库查询简介

    利用Connection对象的createStatement方法建立Statement对象,利用Statement对象的executeQuery()方法执行SQL查询语句进行查询,返回结果集,再形如g ...

  3. Linux的一些命令

    程序 # rpm -qa                # 查看所有安装的软件包 系统 # uname -a               # 查看内核/操作系统/CPU信息 # head -n 1 / ...

  4. .NET 配置文件简单使用

    当我们开发系统的时候要把一部分设置提取到外部的时候,那么就要用到.NET的配置文件了.比如我的框架中使用哪个IOC容器需要可以灵活的选择,那我就需要把IOC容器的设置提取到配置文件中去配置.实现有几种 ...

  5. C#写文本日志帮助类(支持多线程)

    代码: using System; using System.Configuration; using System.IO; using System.Threading.Tasks; namespa ...

  6. 使用VS开发C语言

    在嵌入开发板上做了一段时间的C语言开发后,今天突然心血来潮,想起大学时期在TurboC和TC3下写代码的情形.大一时宿舍里有台386(在当时是算比较先进的了),大一大二基本上都在玩DOS和WIN31. ...

  7. 【Unity】13.1 场景视图中的GI可视化

    分类:Unity.C#.VS2015 创建日期:2016-05-19 一.简介 在场景视图中设计不同的场景内容时,可以根据需要勾选相关的渲染选项,以便让场景仅显示其中的一部分或者全部渲染效果. 在这些 ...

  8. HDU 2577---How to Type

    HDU  2577 Description Pirates have finished developing the typing software. He called Cathy to test ...

  9. jsp中自定义Taglib案例

    一.使用TagSupport类案例解析 1.自定义Tag使用jdbc连接mysql数据库 1.1定义标签处理器类 package com.able.tag; import java.sql.Conne ...

  10. Maven仓库分类

    MAVEN仓库分类 Maven仓库分为:本地仓库+远程仓库两大类 远程仓库又分为:中央仓库+私服+其它公共远程仓库 1,在Maven中,任何一个依赖.插件或者项目构建的输出,都可以称之为构件 2,Ma ...