Java using commos-fileupload to implement file upload and download instance resolution _java

Source: Internet
Author: User
Tags uuid create database

First of all to introduce a file upload

Entity classes

Import Java.sql.Timestamp; /** * * * @Decription File Upload entity class */public class Upfile {private string id;//ID primary key uses UUID to randomly generate private string uuidname ; UUID name private string filename;//file name private string Savepath; Save path private Timestamp uploadtime; Upload time private string description;//file to describe private strings username; 
User name 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

<%@ 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" >  

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 re 
Sponse) throws Servletexception, IOException {doPost (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/ /Judgment form is not composed of multiple parts if (! ServletfileuPload.ismultipartcontent (Request) {Request.setattribute ("msg", "Table single setting error, check the Enctype property is set correctly"); 
Request.getrequestdispatcher ("/upload.jsp"). Forward (request, response); 
return; 
//is a multiple-part acquisition and traversal returns a file Upload object containing all uploaded information try {upfile upfile=webuntil.upload (request); 
Upfileservice upfileservice=new Upfileserviceimpl (); 
Boolean flag=upfileservice.add (Upfile); 
if (flag) {Request.setattribute ("msg", "Upload successful"); 
Request.getrequestdispatcher ("/upload.jsp"). Forward (request, response); 
return; 
}else{Request.setattribute ("msg", "Upload failed, please try again"); 
Request.getrequestdispatcher ("/upload.jsp"). Forward (request, response); 
return; 
}}catch (Filesizelimitexceededexception e) {e.printstacktrace (); 
Request.setattribute ("MSG", "Single file size, exceeding maximum limit"); 
Request.getrequestdispatcher ("/upload.jsp"). Forward (request, response); 
return; 
catch (Sizelimitexceededexception e) {e.printstacktrace (); 
Request.setattribute ("MSG", "Total file size, exceeding maximum limit"); Request.getrequestdispatcher ("/upload.jsp"). Forward (Request, response); 
return; } 
} 
}

Tool Class

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; /** * File Upload Tool class * @Decription TODO */public classWebuntil {/** * File Upload method * @param request requests Parameter incoming * @return returns a Upfile object * @throws filesizelimitexceededexception * Throws Sizelimitexceededexception * @throws IOException * * public static upfile upload (HttpServletRequest request) thro 
WS Filesizelimitexceededexception, sizelimitexceededexception {upfile upfile=new upfile (); 
Arraylist<string> filelist=initlist (); 
try {//Get Disk File Object factory diskfileitemfactory factory=new diskfileitemfactory (); 
String tmp=request.getsession (). Getservletcontext (). Getrealpath ("/tmp"); 
SYSTEM.OUT.PRINTLN (TMP); 
Initial chemical Plant setfactory (factory,tmp); 
Get File Upload parser servletfileupload upload=new servletfileupload (Factory); 
Initialization parser setupload (upload); 
Get file List collection List<fileitem> list = upload.parserequest (request); Traversal for (Fileitem items:list) {//judge is not a normal table single object if (Items.isformfield ()) {//Get the name String of the uploaded form Fieldname=items.getf 
Ieldname (); 
Value String fieldvalue=items.getstring ("UTF-8"); To determine if ("username". Equals (FieldName)) {//Setting Upfile.setusername (Fieldvalue); 
}else if ("description". Equals (FieldName)) {//Set properties Upfile.setdescription (Fieldvalue); 
}else{//Is the file ready to upload//get filename String filename=items.getname (); 
Handle the difference in filename obtained because of browser differences int index=filename.lastindexof ("\"); 
if (index!=-1) {filename=filename.substring (index+1); 
//Generate random filename String uuidname=generatefilename (filename); 
Gets the uploaded file path String savepath=request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/upload"); 
Gets the input stream in the request object InputStream in = Items.getinputstream (); 
The files are scattered and stored in different paths to find the path Savepath=generaterandomdir (savepath,uuidname); 
Copy file UploadFile (in,savepath,uuidname); 
String Id=uuid.randomuuid (). toString (); 
Upfile.setid (ID); 
Upfile.setsavepath (Savepath); 
Upfile.setuuidname (Uuidname); 
Upfile.setfilename (filename); 
Clear Cache Items.delete (); 
}}catch (Fileuploadbase.filesizelimitexceededexception e) {//throws an exception throw E; 
The catch (Fileuploadbase.sizelimitexceededexception e) {//throws an exception throw E; }catch (FileUploadexception e) {e.printstacktrace (); 
catch (Unsupportedencodingexception e) {e.printstacktrace (); 
catch (IOException e) {e.printstacktrace (); 
catch (Exception e) {e.printstacktrace (); 
return upfile; /** * Initialization File list * @return * * private static arraylist<string> initlist () {arraylist<string> list=new Ar 
Raylist<string> (); 
List.add (". jpg"); 
List.add (". rar"); 
List.add (". txt"); 
List.add (". png"); 
return list; /** * Copy file * @param input stream in items * @param savepath save path * @param uuidname file name */private static void UploadFile ( 
InputStream in, String Savepath, String uuidname) {//Get files file file=new filename (savepath, uuidname); 
OutputStream out = null; 
try {int len=0; 
byte [] buf=new byte[1024]; 
Gets the output stream 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 (); /** * generates a random store path * @param savepath save path * @param uuidname generated UUID name * @return * Use hashcode complete */Private STA 
Tic String Generaterandomdir (String Savepath, String uuidname) {//Convert to Hashcode System.out.println ("Upload path" +savepath); 
System.out.println ("Uuidname" +uuidname); 
int Hashcode=uuidname.hashcode (); 
Container StringBuilder sb=new StringBuilder (); 
while (hashcode>0) {//tmp=hashcode&0xf; int 
Sb.append ("/"); 
Sb.append (tmp+ ""); 
hashcode=hashcode>>4; 
///stitching The new Path String path=savepath+sb.tostring (); 
SYSTEM.OUT.PRINTLN ("path" +path); 
File File=new file (path); 
The judgment path does not exist if (!file.exists ()) {//does not exist to create the file.mkdirs (); 
//return path to save; /** * Generates a new filename * @param uuidname random ID name * @param filename Original name * @return/private static String Generatefilenam E (string filename) {string Uuidname=uuid.randomuuid (). ToString (); 
Return Uuidname.replace ("-", ""). ToString () + "_" +filename; /** * Initialization parser * @param upload/private static void Setupload (Servletfileupload upload) {//Set character encoding Upload.sethe 
Aderencoding ("Utf-8"); 
Set File size Upload.setfilesizemax (1024*1024*20); 
Set Total file size Upload.setsizemax (1024*1024*50); Set Progress Listener Upload.setprogresslistener (new Progresslistener () {public void update (long pbytesread, long pcontentlength, I 
NT Pitems) {System.out.println ("read: +pbytesread+"), Total: "+pcontentlength+", "+pitems+"); 
} 
}); /** * Factory Initialization method * @param factory * @param tmp buffer directory */private static void Setfactory (Diskfileitemfactory factory, St 
Ring tmp) {///configuration initialization value buffer Factory.setsizethreshold (1024*1024); 
File File=new file (TMP); 
Set buffer directory factory.setrepository (file); } 
}

Two file downloads

Servlet

public class Downupfileservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse R 
Esponse) throws Servletexception, IOException {doPost (request, response); public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {/ 
/Get ID String id=request.getparameter ("id"); 
The interface of the business layer Upfileservice upfileservice=new Upfileserviceimpl (); 
Find this object upfile Upfile=upfileservice.findupfilebyid (ID) based on ID; 
if (upfile==null) {return; 
//Get the real name of the file String filename=upfile.getfilename (); 
If there is Chinese in the filename, you need to turn the code, otherwise there is no filename filename=urlencoder.encode (filename, "utf-8"); 
The changed name String Uuidname=upfile.getuuidname (); 
Save path String Savepath=upfile.getsavepath (); 
File File=new file (savepath,uuidname); 
Determine if the file exists if (!file.exists ()) {Request.setattribute ("msg", "The downloaded file expires"); 
Request.getrequestdispatcher ("/index"). Forward (request, response); 
Return //Set File Download response header information Response.setheader ("Content-dispositIon "," attachement;filename= "+filename); 
Using IO stream output 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 (); } 
}

Database

Create database upload_download_exercise; 
Use upload_download_exercise; 
CREATE TABLE upfiles ( 
ID varchar (100),////using UUID 
to generate uuidname varchar (255),//uuid plus the original filename 
filename varchar ( 100),//real filename 
savepath varchar (255),//save path 
uploadtime timestamp,//upload time 
description varchar (255),//description 
username varchar (10) on the descendants 

The above is a small set to share the Java use Commos-fileupload to achieve file upload and download related content, I hope to help.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.