I. Overview of the course
In the development of Web application system, file Upload function is a very common function, today to talk about the Javaweb file upload function related to the implementation of technology, and with the rapid development of Internet technology, users of the experience of the site more and more demanding, in the file Upload function technology also appeared many innovative points, For example, the asynchronous upload file, drag-and-drop upload, paste upload, upload progress monitoring, file thumbnails, large file breakpoint continued, large file seconds and so on.
The basics needed for this course:
Understanding the basic HTTP protocol content
Basic IO Flow Operation technology
Servlet Basics
Basic knowledge of Javascript/jquery technology
Second, the basis of file upload
For file uploads, the browser submits the file as a stream to the server in the process of uploading, and all streaming data is carried to the server side with the HTTP request. Therefore, the file upload request content format to be able to understand the basic.
File Upload page:
<form action= "/itheimaupload/uploadservlet" method= "post" enctype= "Multipart/form-data" >
Please select the file to upload:< Input type= "file" name= "Attach"/><br/> <input type= "Submit" value=
"submitted"/>
</form>
HTTP request content:
Third, Java background use servlet to receive files
If you use the servlet to get the input stream of uploaded files and then parse the request parameters inside, it is more troublesome, so the general backstage chooses to use the Apache Open Source Tool common-fileupload This file upload component.
Java Background code: Commons-fileupload Component Upload file public class Uploadservlet extends HttpServlet {public void doget (
HttpServletRequest request, HttpServletResponse response) throws Servletexception, IOException {//1. Configure caching
Diskfileitemfactory factory = new Diskfileitemfactory (1*1024*1024,new File ("c:/tempfiles/"));
2. Create Servlefileupload object Servletfileupload SFU = new Servletfileupload (factory);
Resolve file name Chinese problem sfu.setheaderencoding ("Utf-8"); 3. Parse try {list<fileitem> List = sfu.parserequest (request);//Parse All content if (List!=null) {for (Fileitem item:list) {//sentenced is the normal form parameter if (Item.isformfield ()) {//normal form parameter//Get form's name attribute string fieldName = Item.getfieldname ();//Get form parameter value string
Value = item.getstring ("Utf-8");
}else{//File if (Item.getname ()!=null &&!item.getname (). Equals ("")) {//Save to server hard drive
Fileutils.copyinputstreamtofile (Item.getinputstream (), New File ("c:/targetfiles/" +item.getname ());
Item.delete ();
catch (Fileuploadexception e) {e.printstacktrace ()}}} public void DoPost (HttpservLetrequest request, HttpServletResponse response) throws Servletexception, IOException {doget (request, response);}
Iv. Use Webuploader upload components
File upload the front end of the page we can choose to use some of the more useful upload components, such as Baidu's Open source component Webuploader, this component can basically meet the file upload some of the day-to-day functions required, such as asynchronous upload files, drag-and-drop upload, paste upload, upload progress monitoring, file thumbnails, Even large file breakpoints continue to pass, large file seconds.
Download the Webupload component
http://fex.baidu.com/webuploader/to webupload website Download Webupload Package
WEBUPLOAD directory structure:
Basic File Upload demo (including upload progress)
Front
1.1 in the page to import the required Css,js
<link rel= "stylesheet" type= "Text/css" href= "${pagecontext.request.contextpath}/css/webuploader.css"
>
<script type= "Text/javascript"
src= "${pagecontext.request.contextpath}/js/jquery-1.10.2.min.js" > </script>
<script type= "Text/javascript"
src= "${pagecontext.request.contextpath}/js/ Webuploader.js "></script>
1.2 Write upload page tags
<!--upload div-->
<div id= "uploader" >
<!--display file list information--> <ul id=
"FileList" ></ul >
<!--Select File area-->
<div id= "Filepicker" > click Select File </div>
</div>
1.3 Writing Webupload Code
<script type= "Text/javascript" >//1. Initialize webupload, and configure global parameters var uploader = webuploader.create ({//flashk control's address SWF : "${pagecontext.request.contextpath}/js/uploader.swf",//Background Submit address server: "${pagecontext.request.contextpath}/
Uploadservlet ",//Select the label of the file control pick:" #filePicker ",//automatically upload file Auto:true,}); 2. After selecting files, the file information queue shows//registers filequeued events: Triggers//File after the file is added to the queue: represents the currently selected file Uploader.on ("filequeued", function (file) {// Append file information div $ ("#fileList"). Append ("<div id=" "+file.id+" ' class= ' FileInfo ' ><span> "+file.name+" </span
><div class= ' state ' > Waiting to upload ... </div><span class= ' text ' ></span></div> ');
}); 3. Registration Upload Progress Monitor//file: Uploading the file//percentage: The current rate of progress. The maximum is 1. For example: 0.2 Uploader.on ("Uploadprogress", function (file,percentage) {var id = $ ("#" +file.id);//Update status information Id.find ("
Div.state "). Text (" Upload ... ");
Update upload percent Id.find ("Span.text"). Text (Math.Round (percentage*100) + "%");
}); 4. Registration upload Complete Listening//file: Uploaded file//response: Back in the background data, in JSON format returned Uploader.on ("Uploadsuccess", Function (File,response){//Update status information $ ("#" +file.id). Find ("Div.state"). Text ("Upload complete");
2 Back-end servlet code
Diskfileitemfactory factory = new Diskfileitemfactory ();
Servletfileupload SFU = new Servletfileupload (factory);
Sfu.setheaderencoding ("Utf-8");
try {
list<fileitem> items = sfu.parserequest (request);
for (Fileitem item:items) {
if (Item.isformfield ()) {
//General Information
}else{//
file information
//Decision only files need to be saved for processing
System.out.println ("File name Received:" +item.getname ());
Copy files to the background of the hard drive
Fileutils.copyinputstreamtofile (Item.getinputstream (), New file (serverpath+ "/" +item.getname ()) );
System.out.println ("File Save Succeeded");}}
catch (Fileuploadexception e) {
e.printstacktrace ();
}
Generate thumbnail images of pictures
Key point: Call the Uploader.makethumb () method to generate thumbnails
Uploader.on ("filequeued", function (file) {
//Append file information div
$ ("#fileList"). Append ("<div id=" "+file.id+" " class= ' fileInfo ' ><span> ' +file.name+ ' </span><div class= ' state ' > Waiting to upload ... </div ><span class= ' text ' ></span></div> ');
Manufacturing picture thumbnails: Calling Makethumb () method
//error: Manufacturing thumbnails failed
//src: path uploader.makethumb of thumbnails
(File,function (ERROR,SRC) {
var id = $ ("#" +file.id);
If it fails, the "Cannot preview" if
(error) {
id.find ("img") is displayed. ReplaceWith ("Cannot preview");
Successful, the thumbnail is displayed to the specified location
id.find ("img"). attr ("src", src);
})
;
Drag, paste upload
1 page to add the div of the drag area
<!--upload div-->
<div id= "uploader" >
<!--file drag area--> <div id= "
dndarea" >
<p> Drag the file directly to this place can automatically upload </p>
</div>
<!--display file list information-->
<ul id= "FileList" > </ul>
<!--Select File area-->
<div id= "Filepicker" > click Select File </div>
</div>
2 Add Drag function parameters to the global configuration parameter of Webuploader
1. Initialize webupload, and configure global parameters
var uploader = webuploader.create (
{
//flashk control's address
swf: "${ Pagecontext.request.contextpath}/js/uploader.swf ",
//Background Submit address
server:" ${pagecontext.request.contextpath} /uploadservlet ",
//Select the label of the file control
pick:" #filePicker ",//
automatically upload file
auto:true,
//Open drag function, specify drag area
DND: "#dndArea",
//Disable drag-and-drop functionality elsewhere on the page to prevent pages from opening files directly
disableglobaldnd:true
//opening sticky features
paste: "# Uploader "
}
);
Large File Block upload
1 Add the block upload parameter in the Webuploader global parameter
1. Initialize webupload, and configure global parameters
var uploader = webuploader.create (
{
//flashk control's address
swf: "${ Pagecontext.request.contextpath}/js/uploader.swf ",
//Background Submit address
server:" ${pagecontext.request.contextpath} /uploadservlet ",
//Select the label of the file control
pick:" #filePicker ",//
automatically upload file
auto:true,
//Open drag function, specify drag area
DND: "#dndArea",
//Disable drag-and-drop functionality elsewhere on the page to prevent pages from directly opening file
disableglobaldnd:true,
//opening sticky features
paste: "# Uploader ",//block
upload Settings/
whether the block upload
chunked:true,
//per block file size (default 5M)
chunksize:5*1024*1024, //Open several concurrent threads (default 3) Threads:3///////////////////
turn
on the
next file Preparenextfile:true} When uploading the current file
;
2 monitor uploaded files for three time points
After adding the above three configurations, you will find that when the file is over 5M, Webuploader automatically sends the file to the background in several requests
Each block request, contains the information:
Three important points of time that can be tapped for file block uploads.
Before-send-file: Call Before-send before all blocks are sent
: if there is a chunk, call After-send-file before each chunk is sent
: Call//5 after all the block-forwarding is complete
. Monitor file upload three points (note: This code must be placed before webuploader.create)
//Time point 1:: All blocks are uploaded before (1. Can calculate the unique mark of the file; 2. Can be judged whether seconds pass)
//Time point 2: If the block is uploaded, each chunk is uploaded before (1. Ask the background whether the block has been saved successfully, for the continuation of the breakpoint)
//Time point 3: After all the blocks uploaded successfully (1. Notify the background for the integration of block files)
WebUploader.Uploader.register ({
"before-send-file": "Beforesendfile",
"Before-send": "Beforesend",
"After-send-file": "Aftersendfile"
},{
//Time point 1:: All blocks are uploaded before the call to this function
beforesendfile:function () {
/ /1. A unique token for a computed file that is used for breakpoint continuation and second pass
//2. Request whether the file has been saved in the background, if it exists, skip the file, implement the seconds function
},
//Time point 2: If there is a chunk upload, then call this function before each chunk is uploaded
beforesend:function () {
//1. Request background to save the current chunking, if present, skip the chunk file, implement the breakpoint continuation function
},
//Time point 3: Call this function after all blocks are uploaded successfully
aftersendfile:function () {
//1. If blocks are uploaded, all block files are merged through the background
);
Before-send-file Logic:
Use the Md5file () method to compute a unique tag for
a file//function to receive a deferred
beforesendfile:function (file) {
//Create a deffered
var deferred = Webuploader.deferred ();
1. Compute a unique tag for a file that is used for breakpoint continuation and second pass
(new Webuploader.uploader ()). Md5file (file,0,5*1024*1024).
Progress (function ( Percentage) {
$ ("#" +file.id). Find ("Div.state"). Text ("Getting file information ...");
Then (function (val) {
uniquefiletag = val;
$ ("#" +file.id). Find ("Div.state"). Text ("Successfully obtain file information");
Only if the file information is successful, do the next step
deferred.resolve ();
};
alert (uniquefiletag);
2. Request whether the file has been saved in the background, if it exists, skip the file, realize the second pass function
//return deffered returns
deferred.promise ();
}
Before-send Logic:
Sends a unique token for the current file to the background to create a directory
beforesend:function () {
///With the current file's unique tag to the background to create a directory
in which to save the file chunking in the background This.owner.options.formData.fileMd5 = FileMd5;
}
3 The background needs to save all the block files
Create a directory for each file and save all the block files for this file
//To determine if
(chunks!=null) {
System.out.println ("Chunk handling ...") has been uploaded;
Make a block upload
//Create a temporary directory to save all the block files file
chunksdir = new File (serverpath+ "/" +filemd5);
if (!chunksdir.exists ()) {
chunksdir.mkdir ();
}
if (chunk!=null) {
//save chunk file
chunkfile = new file (Chunksdir.getpath () + "/" +chunk);
Fileutils.copyinputstreamtofile (Item.getinputstream (), chunkfile);
}
4 The foreground notice to merge all the block files in the background
Foreground notice background merge file After-send-file logic: aftersendfile:function (file) {//1. If you block-upload, merge all the block files//request background merge files in the background $.ajax ({type: " POST ", url:" ${pagecontext.request.contextpath}/uploadcheckservlet?action=mergechunks ", data:{//File unique tag fileMd5:
FILEMD5,//file name FileName:file.name}, DataType: "JSON", success:function (response) {alert (response.msg);}
);
///Background Merge all chunking files if ("Mergechunks". Equals (Action)) {System.out.println ("Start merging Files ...");
Merge file String fileMd5 = Request.getparameter ("FileMd5");
String fileName = request.getparameter ("filename");
Read all files inside the directory file F = new file (serverpath+ "/" +filemd5); file[] Filearray = f.listfiles (new FileFilter () {//exclude directory, as long as the file is public boolean accept (file pathname) {if (pathname.isdirecto
Ry ()) {return false;} return true;
}
});
Turn into a set for easy sorting list<file> filelist = new Arraylist<file> (arrays.aslist (Filearray)); Small to large sort collections.sort (filelist, New comparator<file> () {public int compare (file O1, file O2) {if (integer.parse Int (O1.getname ()) < Integer.parseiNT (O2.getname ())) {return-1;} return 1;
}
});
File outputfile = new file (serverpath+ "/" +filename);
Create file Outputfile.createnewfile ();
Output stream FileChannel Outchannel = new FileOutputStream (outputfile). Getchannel ();
Merging FileChannel Inchannel; for (file file:filelist) {Inchannel = new FileInputStream (file). Getchannel (); Inchannel.transferto (0, Inchannel.size ()
, Outchannel);
Inchannel.close ();
Delete the fragment file.delete ();
//Clear Folder File Tempfile = new file (serverpath+ "/" +filemd5);
if (Tempfile.isdirectory () && tempfile.exists ()) {Tempfile.delete ();}//Close stream outchannel.close ();
Response.setcontenttype ("Text/html;charset=utf-8");
Response.getwriter (). Write ("{\" msg\ ": \" merged successfully \ "}"); }
Large file breakpoint continued transmission
On the basis of realizing the block-uploading, it is very simple to realize the continuation of the breakpoint.!!!
Front:
Time point 2: If there is a chunk upload, then call this function before each chunk is uploaded
//block: Represents the current Chunking object
beforesend:function (block) {
//1. Request background to save the current chunk, if present, The block file is skipped and the breakpoint continues to be implemented
var deferred = webuploader.deferred ();
Request whether the background is saved to complete the file information, if it is saved, skip, if not, send the chunk content
$.ajax (
{
type: "POST",
URL: "${ Pagecontext.request.contextpath}/uploadcheckservlet?action=checkchunk ",
data:{
//File unique tag
fileMd5 : FILEMD5,///
current block subscript
chunk:block.chunk,
//current chunking size
chunksize:block.end-block.start
},
dataType: "JSON",
success:function (response) {
if (response.ifexist) {
//block exists, skipping the
chunking Deferred.reject ();
} else{
//block does not exist or incomplete, resend the chunk content
deferred.resolve ();}}
);
carry the unique tag of the current file to the background, for the background to create a directory that holds the file block
this.owner.options.formData.fileMd5 = fileMd5;
return Deferred.promise ();
},
Background:
Check that the chunk exists or is fully saved
private void Checkchunk (HttpServletRequest request,
HttpServletResponse response) throws IOException,
filenotfoundexception {
System.out.println ("Checkchunk ...");
String fileMd5 = Request.getparameter ("FileMd5");
String chunk = request.getparameter ("chunk");
String chunksize = Request.getparameter ("chunksize");
File Checkfile = new file (serverpath+ "/" +filemd5+ "/" +chunk);
Response.setcontenttype ("Text/html;charset=utf-8");
Check if the file exists and the size is consistent if
(Checkfile.exists () && checkfile.length () ==integer.parseint (chunksize)) {
Response.getwriter (). Write ("{\" ifexist\ ": 1}");
else{
Response.getwriter (). Write ("{\" ifexist\ ": 0}");
}
File Second Pass
It is possible to implement the second-pass function before all block requests are!!!
Front:
Beforesendfile:function (file) {
//Create a deffered
var deferred = webuploader.deferred ();
1. Compute a unique tag for a file that is used for breakpoint continuation and second pass
(new Webuploader.uploader ()). Md5file (file,0,5*1024*1024).
Progress (function ( Percentage) {
$ ("#" +file.id). Find ("Div.state"). Text ("Getting file information ...");
Then (function (val) {
fileMd5 = val;
$ ("#" +file.id). Find ("Div.state"). Text ("Successfully obtain file information");
2. Request whether the file has been saved in the background, if it exists, skip the file, realize the second function
$.ajax (
{
type: "POST",
URL: "${ Pagecontext.request.contextpath}/uploadcheckservlet?action=filecheck ",
data:{
//File unique tag
fileMd5: FileMd5
},
DataType: "JSON",
success:function (response) {
if (response.ifexist) {
$ ("#" + file.id). Find ("Div.state"). Text ("Second pass success");
If present, skip the file, and the second pass succeeds
deferred.reject ();
} else{
//Continue uploading
deferred.resolve ()
;}}}); Returns deffered return
deferred.promise ();
},
Background:
Check that the MD5 data for the file exists with the database
private void FileCheck (HttpServletRequest request,
httpservletresponse response) Throws IOException,
filenotfoundexception {
String fileMd5 = Request.getparameter ("FileMd5");
Analog database
map<string,string> db = new hashmap<string,string> ();
Database.put ("576018603F4091782B68B78AF85704A1", "01. Curriculum review. Itcast");
Response.setcontenttype ("Text/html;charset=utf-8");
if (Database.containskey (FILEMD5)) {
response.getwriter (). Write ("{\" ifexist\ ": 1}");
else{
Response.getwriter (). Write ("{\" ifexist\ ": 0}");
}
The above is a small series to introduce the Javaweb file upload download examples (cool file upload technology), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!