Html5+java Large File Upload code

Source: Internet
Author: User

<body><input id= "Fileid"  type= "file"  accept= "Video/*;capture=camera" onchange= "Onfile ( This) "><input id=" btn " type=" button " value=" Commit "><script type=" Text/javascript " >var xhr;function onfile (file)  {var fd = new formdata (); Fd.append (" Filetoupload ",  document.getelementbyid (' Fileid '). Files[0]); Xhr = new xmlhttprequest (); Xhr.open ("POST",  "Http://localhost:8889/TestUp/upservlet");//xhr.setrequestheader ("Content-type", "CharSet =utf-8 "); Xhr.send (fd); xhr.onreadystatechange = processresponse;} Function processresponse () {if (xhr.readystate == 4) {         alert ("End of upload end data stream");         if (xhr.status == 200) {         var infor = xhr.responseText;             alert ("ServiceResponse  =  "+infor" of the end of the device);         }    }}</ Script></body>
package com.yjm.up;import java.io.file;import java.io.fileoutputstream;import  java.io.ioexception;import java.io.inputstream;import java.util.list;import  javax.servlet.servletexception;import javax.servlet.http.httpservlet;import  javax.servlet.http.httpservletrequest;import javax.servlet.http.httpservletresponse;import  org.apache.commons.fileupload.fileitem;import org.apache.commons.fileupload.disk.diskfileitemfactory; import org.apache.commons.fileupload.servlet.servletfileupload;public class upservlet  Extends httpservlet {public void dopost (httpservletrequest request,  Httpservletresponse response) throws servletexception, ioexception {//  get the saved directory of uploaded files, The uploaded files are stored in the Web-inf directory, not directly accessible by the outside world, to ensure the security of the uploaded files String savepath = this.getservletcontext (). Getrealpath (" /web-inf/upload "); File file = new file (Savepath); SYSTEM.OUT.PRINTLN ("Test ....")");//  determine if the saved directory of the uploaded file exists if  (!file.exists ()  && !file.isdirectory ())  { System.out.println (savepath +  "directory does not exist, need to create");//  Create directory File.mkdir ();}   Message Tip string message =  "";try {//  use Apache File Upload component to process file upload steps:// 1, Create a diskfileitemfactory factory diskfileitemfactory factory = new diskfileitemfactory ();// 2 , create a File Upload Parser servletfileupload upload = new servletfileupload (factory);//  Solve the upload file name of the Chinese garbled upload.setheaderencoding ("UTF-8"),// 3, determine whether the submitted data is the data upload form if  (! Servletfileupload.ismultipartcontent (Request)  {//  get the data return in the traditional way;}  4, using the Servletfileupload parser to parse the uploaded data, the parse result returns a List<fileitem> collection, each fileitem corresponding to the input of a form form list< Fileitem> list = upload.parserequest (Request);for  (fileitem item : list)  {//  If the data if  (Item.isformfield ()) of the normal input is encapsulated in Fileitem  {String name =  Item.getfieldname ();//  solve common inputThe data of the Chinese garbled Problem string value = item.getstring ("UTF-8");// value = new string ( Value.getbytes ("Iso8859-1"), "UTF-8"); System.out.println (name +  "="  + value);}  else {//  if the Fileitem in the package is uploaded file//  get uploaded file name, String filename = item.getname (); SYSTEM.OUT.PRINTLN (filename);if  (filename == null | |  filename.trim (). Equals (""))  {continue;   NOTE: Different browser submissions are not the same file name, some browsers submitted by the file name is with a path, such as:// c:\a\b\1.txt, and some just simple file name, such as:1.txt//  Process the path portion of the file name that gets uploaded files, leaving only the file name section filename = filename.substring (filename.lastindexof ("\ \")  + 1) ;//  gets the input stream of the uploaded file in item inputstream in = item.getinputstream ();//  Create a file output stream Fileoutputstream out = new fileoutputstream (savepath +  "\ \" +  FileName);//  Create a buffer byte buffer[] = new byte[1024 * 1024];//  Identifies whether the data in the input stream has been read int len = 0;//  loop reads the input stream into the bufferZone, (len=in.read (buffer)) >0 means that in inside there is also data while  ((len = in.read (buffer))  > 0)   {//  uses the FileOutputStream output stream to write the buffer's data to the specified directory (savepath +  "\ \"// + filename) Out.write ( Buffer, 0, len);} Out.flush ();//  closes the input stream In.close ();//  closes the output stream Out.close ();//  deletes the temporary file generated when the file is uploaded item.delete (); message  =  "File Upload successful! ";}}}  catch  (exception e)  {message =  "File upload failed! "; E.printstacktrace ();} Request.setattribute ("message",  message), Request.getrequestdispatcher ("/message.jsp"). Forward (Request,  response);}}

The Java package used is more than 1G upload

Commons-fileupload-1.2.1.jar

Commons-io-1.3.2.jar


Xhr.setrequestheader ("Content-type", "application/octet-stream;charset=utf-8"); This cannot be added

Html5+java Large File Upload code

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.