JAVA應用commos-fileupload完成文件上傳與下載實例解析。本站提示廣大學習愛好者:(JAVA應用commos-fileupload完成文件上傳與下載實例解析)文章只能為提供參考,不一定能成為您想要的結果。以下是JAVA應用commos-fileupload完成文件上傳與下載實例解析正文
起首給年夜家引見一文件的上傳
實體類
import java.sql.Timestamp; /** * * @Decription 文件上傳實體類 * */ public class Upfile { private String id;// ID主鍵 應用uuid隨機生成 private String uuidname; // UUID稱號 private String filename;//文件稱號 private String savepath; // 保留途徑 private Timestamp uploadtime; // 上傳時光 private String description;// 文件描寫 private String username; // 用戶名 public Upfile() { super(); } public Upfile(String id, String uuidname, String filename, String savepath, Timestamp uploadtime, String description, String username) { super(); this.id = id; this.uuidname = uuidname; this.filename = filename; this.savepath = savepath; this.uploadtime = uploadtime; this.description = description; this.username = username; } public String getDescription() { return description; } public String getFilename() { return filename; } public String getId() { return id; } public String getSavepath() { return savepath; } public Timestamp getUploadtime() { return uploadtime; } public String getUsername() { return username; } public String getUuidname() { return uuidname; } public void setDescription(String description) { this.description = description; } public void setFilename(String filename) { this.filename = filename; } public void setId(String id) { this.id = id; } public void setSavepath(String savepath) { this.savepath = savepath; } public void setUploadtime(Timestamp uploadtime) { this.uploadtime = uploadtime; } public void setUsername(String username) { this.username = username; } public void setUuidname(String uuidname) { this.uuidname = uuidname; } }
頁面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'upload.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>文件上傳</h1> <form action="${pageContext.request.contextPath }/upload" method="post" enctype="multipart/form-data"> <table> <tr> <td> 上傳用戶名:</td> <td><input type="text" name="username"/></td> </tr> <tr> <td> 上傳文件:</td> <td><input type="file" name="file"/></td> </tr> <tr> <td> 描寫:</td> <td><textarea rows="5" cols="50" name="description"></textarea></td> </tr> <tr> <td><input type="submit" value="上傳開端"/></td> </tr> </table> </form> <div>${msg }</div> <a href="${pageContext.request.contextPath }/index.jsp">前往主頁</a> </body> </html>
Servlet
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.itheima.domain.Upfile; import com.itheima.exception.MyException; import com.itheima.service.UpfileService; import com.itheima.service.impl.UpfileServiceImpl; import com.itheima.untils.WebUntil; public class UploadFileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //斷定表單是否是多個部門構成的 if(!ServletFileUpload.isMultipartContent(request)){ request.setAttribute("msg", "表單個設置毛病,請檢討enctype屬性是能否設置准確"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; } //是多部門構成的就獲得並遍歷前往一個文件上傳對象,包括上傳的一切信息 try { Upfile upfile=WebUntil.upload(request); UpfileService upfileService=new UpfileServiceImpl(); boolean flag=upfileService.add(upfile); if(flag){ request.setAttribute("msg", "上傳勝利"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; }else{ request.setAttribute("msg", "上傳掉敗,請重試"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; } }catch (FileSizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("msg", "單個文件年夜小 ,跨越最年夜限制"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; } catch (SizeLimitExceededException e) { e.printStackTrace(); request.setAttribute("msg", "總文件年夜小 ,跨越最年夜限制"); request.getRequestDispatcher("/upload.jsp").forward(request, response); return ; } } }
對象類
import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException; import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.ProgressListener; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.itheima.domain.Upfile; import com.itheima.exception.MyException; /** * 文件上傳對象類 * @Decription TODO * */ public class WebUntil { /** * 文件上傳的辦法 * @param request 要求參數傳入 * @return 前往一個Upfile對象 * @throws FileSizeLimitExceededException * @throws SizeLimitExceededException * @throws IOException */ public static Upfile upload(HttpServletRequest request) throws FileSizeLimitExceededException, SizeLimitExceededException { Upfile upfile=new Upfile(); ArrayList<String> fileList=initList(); try { //獲得磁盤文件對象工場 DiskFileItemFactory factory=new DiskFileItemFactory(); String tmp=request.getSession().getServletContext().getRealPath("/tmp"); System.out.println(tmp); //初始化工場 setFactory(factory,tmp); //獲得文件上傳解析器 ServletFileUpload upload=new ServletFileUpload(factory); //初始化解析器 setUpload(upload); //獲得文件列表聚集 List<FileItem> list = upload.parseRequest(request); //遍歷 for (FileItem items : list) { //斷定 是否是通俗表單個對象 if(items.isFormField()){ //獲得上傳表單的name String fieldName=items.getFieldName(); //value String fieldValue=items.getString("UTF-8"); //斷定 if("username".equals(fieldName)){ //設置 upfile.setUsername(fieldValue); }else if("description".equals(fieldName)){ //設置屬性 upfile.setDescription(fieldValue); } }else{ //是文件就預備上傳 //獲得文件名 String filename=items.getName(); //處置由於閱讀器分歧而招致的 取得 的 文件名的 差別 int index=filename.lastIndexOf("\\"); if(index!=-1){ filename=filename.substring(index+1); } //生成隨機的文件名 String uuidname=generateFilename(filename); //獲得上傳的文件途徑 String savepath=request.getSession().getServletContext().getRealPath("/WEB-INF/upload"); //獲得要求對象中的輸出流 InputStream in = items.getInputStream(); //將文件打散寄存在分歧的途徑,求前途徑 savepath=generateRandomDir(savepath,uuidname); //復制文件 uploadFile(in,savepath,uuidname); String id=UUID.randomUUID().toString(); upfile.setId(id); upfile.setSavepath(savepath); upfile.setUuidname(uuidname); upfile.setFilename(filename); //消除緩存 items.delete(); } } }catch ( FileUploadBase.FileSizeLimitExceededException e) { //拋出出異常 throw e; } catch (FileUploadBase.SizeLimitExceededException e) { //拋出出異常 throw e; }catch (FileUploadException e) { e.printStackTrace(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return upfile; } /** * 初始化文件列表 * @return */ private static ArrayList<String> initList() { ArrayList<String> list=new ArrayList<String>(); list.add(".jpg"); list.add(".rar"); list.add(".txt"); list.add(".png"); return list; } /** * 復制文件 * @param in items中的輸出流 * @param savepath 保留途徑 * @param uuidname 文件名 */ private static void uploadFile(InputStream in, String savepath, String uuidname) { //獲得文件 File file=new File(savepath, uuidname); OutputStream out = null; try { int len=0; byte [] buf=new byte[1024]; //獲得輸入流 out = new FileOutputStream(file); while((len=in.read(buf))!=-1){ out.write(buf, 0, len); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { in.close(); } catch (IOException e) { e.printStackTrace(); } try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 生成隨機的寄存途徑 * @param savepath 保留途徑 * @param uuidname 生成的uuid稱號 * @return * 應用hashcode完成 */ private static String generateRandomDir(String savepath, String uuidname) { //轉化為hashcode System.out.println("上傳途徑"+savepath); System.out.println("UUIDNAME"+uuidname); int hashcode=uuidname.hashCode(); //容器 StringBuilder sb=new StringBuilder(); while(hashcode>0){ //與上15 int tmp=hashcode&0xf; sb.append("/"); sb.append(tmp+""); hashcode=hashcode>>4; } //拼接新的途徑 String path=savepath+sb.toString(); System.out.println("path"+path); File file=new File(path); //斷定途徑存不存在 if(!file.exists()){ //不存在就創立 file.mkdirs(); } //前往保留途徑 return path; } /** * 生成新的文件名 * @param uuidname 隨機的ID名字 * @param filename 本來的名 * @return */ private static String generateFilename( String filename) { String uuidname=UUID.randomUUID().toString(); return uuidname.replace("-", "").toString()+"_"+filename; } /** * 初始化解析器 * @param upload */ private static void setUpload(ServletFileUpload upload) { // 設置 字符編碼 upload.setHeaderEncoding("utf-8"); //設置文件年夜小 upload.setFileSizeMax(1024*1024*20); //設置總文件年夜小 upload.setSizeMax(1024*1024*50); //設置進度監聽器 upload.setProgressListener(new ProgressListener() { public void update(long pBytesRead, long pContentLength, int pItems) { System.out.println("曾經讀取: "+pBytesRead+",總共有: "+pContentLength+", 第"+pItems+"個"); } }); } /** * 工場初始化辦法 * @param factory * @param tmp 緩沖目次 */ private static void setFactory(DiskFileItemFactory factory, String tmp) { /// 設置裝備擺設初始化值緩沖區 factory.setSizeThreshold(1024*1024); File file=new File(tmp); //設置緩沖目次 factory.setRepository(file); } }
二文件下載
Servlet
public class DownupfileServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //獲得ID String id=request.getParameter("id"); //營業層的接口 UpfileService upfileService=new UpfileServiceImpl(); //依據ID查找這個對象 Upfile upfile=upfileService.findUpfileById(id); if(upfile==null){ return; } //獲得文件的真實稱號 String filename=upfile.getFilename(); //假如文件名中有中文,須要轉碼,否則就下載時沒有文件名 filename=URLEncoder.encode(filename, "utf-8"); //更悛改的稱號 String uuidname=upfile.getUuidname(); //保留途徑 String savepath=upfile.getSavepath(); File file=new File(savepath,uuidname); //斷定文件 能否存在 if(!file.exists()){ request.setAttribute("msg", "下載 的文件過時了"); request.getRequestDispatcher("/index").forward(request, response); return; } //設置文件下載呼應頭信息 response.setHeader("Content-disposition", "attachement;filename="+filename); //應用IO流輸入 InputStream in = new FileInputStream(file); ServletOutputStream out = response.getOutputStream(); int len=0; byte [] buf=new byte[1024]; while((len=in.read(buf))!=-1){ out.write(buf, 0, len); } in.close(); } }
數據庫
create database upload_download_exercise; use upload_download_exercise; create table upfiles( id varchar(100), //應用UUID生成 uuidname varchar(255),//uuid加上本來的文件名 filename varchar(100),//真實文件名 savepath varchar(255),//保留途徑 uploadtime timestamp,//上傳時光 description varchar(255),//描寫 username varchar(10) 上傳人 );
以上所述是小編給年夜家分享的JAVA應用commos-fileupload完成文件上傳與下載的相干內容,願望對年夜家有所贊助。