Javaweb series 17 (upload download)

Source: Internet
Author: User
Tags temporary file storage



1, File Upload
(1) What is upload: The client file is uploaded to the server. Like cloud disks.
(2) Implement upload: The servlet does not provide the technology to upload. Requires the use of third-party components for uploading
(3) Technology for uploading:
Jspsmartupload: Suitable for embedding in JSP files that perform upload and download operations
For the Jsp+javabean model, the model one
FILEUPLOAD:MVC development model, model two
FileUpload is a sub-project under Apache Commons to implement the file upload function under the Java environment
Component FileUpload dependent on commons IO components
To implement the third-party technology for uploading, you first need to import the jar package
(4) How to implement upload (required):
First requirement: There is a form, but the method must be a post
The second requirement: must have a file entry, in the file entry must be the Name property <input type= "file" name= "file"/>
The third requirement: Enctype:multipart/form-data in the form
Enctype Default value: application/x-www-form-urlencoded
(5) File upload implementation process (drawing)

(6) Using code to implement file upload
Importing the FileUpload jar package
Use to class Diskfileitemfactory: Disk File Entry Factory
Servletfileupload: Core Upload class
Fileitem: File entry
Step (fixed)
1. Create Disk File entry factory new Diskfileitemfactory ()
2, create the core of the upload class new Servletfileupload (Fileitemfactory fileitemfactory)
3. Use the core upload class to parse the Request object Parserequest (Javax.servlet.http.HttpServletRequest request)
Returns the list collection generic Fileitem
4. Traversing the list collection
5, judge whether Fileitem is a normal item or file upload item
If it is a normal item, get the name and value of the ordinary item
If it is a file upload item, implement the file upload code

(7) Use of Core API
Diskfileitemfactory: Disk File Entry Factory
Construction method
Diskfileitemfactory ()
There are two methods of setting
Setsizethreshold (int sizethreshold)
Setrepository (Java.io.File repository)
diskfileitemfactory (int sizethreshold, Java.io.File repository)
First parameter: Buffer size 10k;
Second parameter: Temporary file storage path, upload file size exceeds buffer size to produce temporary file

Servletfileupload: Core Upload class
Construction method Servletfileupload (fileitemfactory fileitemfactory)
Parse Request object: Parserequest (Javax.servlet.http.HttpServletRequest request)
Returns the list collection, generic Fileitem

    settings file name is in Chinese, set code: setheaderencoding (java.lang.String encoding)
    To set the size of a single file upload: Setfilesizemax (long Filesizemax)
    Set the total size of all file uploads: Setsizemax (long Sizemax)
    Fileitem Interface: File entry
    Isformfield (): Determines whether a normal item or a file item is true and False, if TRUE indicates a normal item, If False indicates a file upload entry
    getfieldname (): Gets the name of the generic item
    getString (): Gets the value of the normal item input
    getString (java.lang.String encoding): Set encoding
    getName (): Get the Upload file name (plus path)
    in some browsers, get just the file name without path 1.txt
    getinputstream (): The input stream to get the submitted file
     Delete (): Remove temporary files

    (8) Exercise: JS control multi-File upload
    There are two buttons: Upload and add
    when click Increases, Add a file Upload item and delete button
    single click Delete, delete the delete button on the same line
    click Upload, and upload all the files on the page to the server
     JS Code
  //Add method
    function add1 () {
   //Get div
    var divv = document.getElementById ("DIVV");
   //write HTML code to div
    divv.innerhtml + = "<div><input type= ' file ' name= ' file1 '/ > <input type= ' button ' value= ' del ' onclick= ' Del1 (this); ' /></div> ";
}

   /delete action
    function Del1 (WHO) {
   //Get the div where the Del button is located
    var div = who.parentnode;
   /delete div
    var divv = Div.parentnode;
    Divv.removechild (div);  
   }
    (9) Issue resolution for uploads
Problems with duplicate names of     files
    If you upload files with the same file name multiple times, the last file you uploaded will overwrite the previous file
    workaround:
    Add a random string after the file name   Abbcdfdfer_1.txt
    get a random string: The UUID gets a unique string
   //Get a unique string using the UUID
    string uuid = Uuid.randomuuid (). toString ();
   //Add the value of the UUID before the file   uuid_filename
    filename = uuid+ "_" +filename;

All uploaded files will be placed in a folder, if there are many files, read and write very slowly
In enterprise-level development
Separation according to time: According to the Day of the month
Detach according to User: e.g. Zhang San upload file to Zhang San
Separation according to the number of files: 3,000 files per folder
Implementation of the algorithm using directory separation
First get the file's unique filename
Based on this unique file name. hashcode () operation, get a unique int value
Use the resulting unique value,& 0xf results as the first level of the directory
Use int value, move right four bit, then & 0xf, result as second level directory
int 32 bits, how is it represented in the computer?
Each four bits represents a paragraph, 8 paragraphs

2, the download of the file
(1) file download several ways: two kinds of
Using hyperlinks directly to implement <a href= "file path" ></a>
This method is not good, the picture format opens directly, and the ZIP format will prompt to download
Write code implementation download
Steps
Create a disk File item factory
Diskfileitemfactory factory = new Diskfileitemfactory ();
Creating a core upload class
Servletfileupload upload = new Servletfileupload (factory);
Upload.setheaderencoding ("Utf-8");
Parsing the Request object
list<fileitem> list = upload.parserequest (request);
Create a Resource object
Resource res = new Resource ();
Traversing the list collection
for (Fileitem fileitem:list) {
Determine if an ordinary entry
if (Fileitem.isformfield ()) {
String des = fileitem.getstring ("Utf-8");
System.out.println (DES);
Res.setdes (DES);
} else {//File Upload Item
Get upload file name C:\a\a.txt
String filename = Fileitem.getname ();
int lens = Filename.lastindexof ("\ \");
if (Lens! =-1) {
filename = filename.substring (lens+1);
}
Get a random string
String uuid = Uuid.randomuuid (). toString ();
String Uuidname = uuid+ "_" +filename;

Get the full path to the uploaded folder
String path = Getservletcontext (). Getrealpath ("/uploadfile");

Get the path after separation
String url = uploadutils.getpath1 (uuidname);
Determine if the folder exists and if it does not exist, you need to create
File File = new file (Path+url);
if (!file.exists ()) {
File.mkdirs ();
}
Get upload file
InputStream in = Fileitem.getinputstream ();
Use the output stream to write files to a folder
OutputStream out = new FileOutputStream (path+url+ "/" +uuidname);
Flow docking
int len = 0;
Byte[] B = new byte[1024];
while ((Len=in.read (b))!=-1) {
Out.write (b, 0, Len);
}
Close the stream
In.close ();
Out.close ();

Set up information for uploads
Res.setuuidname (Uuidname);
Res.setrealname (filename);
Res.setsavepath (Path+url);
(2) Download the code implementation file
Get the path to the file you want to download
String Path = request.getparameter ("filename");
Path = new String (path.getbytes ("iso8859-1"), "Utf-8");
System.out.println ("Path::" +path); C:\1\a.mp3
Get the file name
String filename = path.substring (path.lastindexof ("\ \") +1);
Handling different browser Chinese issues
Solve Chinese garbled problem
The type of browser that gets the current request
String Agent = Request.getheader ("user-agent");

If it's a Firefox browser
if (Agent.contains ("Firefox")) {
Base64 encoding
filename = "=?" UTF-8? B? " +
New Base64encoder (). Encode (Filename.getbytes ("utf-8") + "? =";
} else {//ie browser
filename = urlencoder.encode (filename, "utf-8");
}
Set MIME type
String type = Getservletcontext (). GetMimeType (filename);
Response.setcontenttype (type);
Set Header information
Response.setheader ("Content-disposition", "attachment;filename=" +filename);
Get the input stream to download the file
InputStream in = new FileInputStream (path);
Write to the browser using the output stream
OutputStream out = Response.getoutputstream ();
int len = 0;
Byte[] B = new byte[1024];
while ((Len=in.read (b))!=-1) {
Out.write (b, 0, Len);
}
In.close ();
(3) Exercise: Given any directory, all the files in the directory are displayed (no matter how many layers)
Implementation ideas:
Use to Tree
Tree traversal: Depth-first traversal and breadth-first traversal
The queue can be used to implement tree traversal, the queue features FIFO, first-out
1. Create a queue
-Queue<file> que = new linkedlist<file> ();
-Queue: Offer (e e)
-Out Team: poll ()
<%
Create a file
File root = new file ("F:\\1");
Create a queue
queue<file> qu = new linkedlist<file> ();
Queue the root node
Qu.offer (root);
Determine if the queue is not empty
while (!qu.isempty ()) {
Put the root node out of the team
File File = Qu.poll ();
Get all the files and folders
file[] files = file.listfiles ();
Traverse
for (File f:files) {
Determine if it is a file, if the file is displayed directly, not the file continues to queue
if (F.isfile ()) {
%>
<a href= "/day20/downlist?filename=<%=f.getcanonicalpath ()%>" ><%=f.getname ()%></a> <br />
<%
} else {//is not a file
Team
Qu.offer (f);
}
}
}
%>
2, the root node into the queue, and then the root node out of the team
3, the root node after the team, you can get the child nodes of the root node
4, the node queue, in the team, to obtain child nodes of the child node
In turn ....
Implementing a File Download

Hashcode operation on file name, return int type
int code1 = Filename.hashcode ();
Use int value & OXF
int d1 = code1 & 0xf;
int values shift right four bits
int code2 = Code1 >>> 4;
&AMP;0XF the Code2 again.
int d2 = Code2 & 0xf;
Return "/" +d1+ "/" +D2;
}













Javaweb series 17 (upload download)

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.