Resumable file upload, html5 front-end implementation, java server implementation, html5java

Source: Internet
Author: User

Resumable file upload, html5 front-end implementation, java server implementation, html5java

  • Resumable upload can prevent accidental uploads of half of files from being downloaded from scratch the next time. There are many resumable uploads on the Internet. This article only records the next available instance from the past to the next, because the production environment is not highly demanding and is provided to one or two people, I have simplified many processes without flash or applet. I only use the new html5 features for browser processing.
  • Key Points
  • Server Method
/*** Get the size of the uploaded file * @ param request * @ param response */public void getChunkedFileSize (HttpServletRequest request, HttpServletResponse response) {// path for storing the file, string currentFilePath = "c: \ uploadFile \ Image \"; PrintWriter print = null; try {request. setCharacterEncoding ("UTF-8"); print = response. getWriter (); String fileName = new String (request. getParameter ("fileName "). getBytes ("ISO-8859-1"), "UTF-8"); String lastModifyTime = request. getParameter ("lastModifyTime"); File file = new File (currentFilePath + fileName + ". "+ lastModifyTime); if (file. exists () {print. print (file. length ();} else {print. print (-1) ;}} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}}

2. File Upload

/***** Resumable upload 1. determine whether a breakpoint file exists first. direct stream upload exists. 3. no new file exists. 4. after the upload is complete, set the file name **/public static void appendUpload2Server (HttpServletRequest request, HttpServletResponse response) {PrintWriter print = null; try {request. setCharacterEncoding ("UTF-8"); print = response. getWriter (); String fileSize = request. getParameter ("fileSize"); long totalSize = StringUtil. toLong (fileSize); RandomAccessFile randomAccessf Ile = null; long currentFileLength = 0; // record the current file size, used to determine whether the file is uploaded successfully String currentFilePath = "c: \ uploadFile \ Image \\"; // record the absolute path of the current file String fileName = new String (request. getParameter ("fileName "). getBytes ("ISO-8859-1"), "UTF-8"); String lastModifyTime = request. getParameter ("lastModifyTime"); File file = new File (currentFilePath + fileName + ". "+ lastModifyTime); // if (file. exists () {randomAccessfile = New RandomAccessFile (file, "rw");} else {// the file does not exist. Create the file named randomAccessfile = new RandomAccessFile (currentFilePath + fileName + ". "+ lastModifyTime," rw ");} // start File Transfer InputStream in = request. getInputStream (); randomAccessfile. seek (randomAccessfile. length (); byte B [] = new byte [1024]; int n; while (n = in. read (B ))! =-1) {randomAccessfile. write (B, 0, n);} currentFileLength = randomAccessfile. length (); // close the file closeRandomAccessFile (randomAccessfile); randomAccessfile = null; // after the entire file is uploaded, modify the file suffix if (currentFileLength = totalSize) {File oldFile = new File (currentFilePath + fileName + ". "+ lastModifyTime); File newFile = new File (currentFilePath + fileName); if (! OldFile. exists () {return; // The renamed file does not exist} if (newFile. exists () {// if a file such as test.txt exists, the new file is stored as test1_timestamp. txt. The file without the extension String newName = fileName is not processed. substring (0, fileName. lastIndexOf (". ") + System. currentTimeMillis () + ". "+ fileName. substring (fileName. lastIndexOf (". ") + 1); newFile = new File (currentFilePath + newName);} if (! OldFile. renameTo (newFile) {oldFile. delete () ;}} print. print (currentFileLength);} catch (Exception e) {e. printStackTrace () ;}}/*** disable Random Access File ** @ param randomAccessfile */public static void closeRandomAccessFile (RandomAccessFile rfile) {if (null! = Rfile) {try {rfile. close () ;}catch (Exception e) {e. printStackTrace ();}}}
  • Jsp page
<Html> 

 
  • Js Code
Var msg = null; var paragraph = 1024*1024*2; // the size of each part Transfer File 2 Mvar blob = null; // vector Blob Object var fileList = null for the sharded data; // The transmitted file var uploadState = 0; // 0: No upload/cancel, 1: uploading, 2: pause // initialize the message box function init () {msg = document. getElementById ("msg");} function uploadFiles () {// set the upload status to 1 uploadState = 1; if (fileList. files. length> 0) {for (var I = 0; I <fileList. files. length; I ++) {var file = fileList. files [I]; uploadFile Init (file, I) ;}} else {msg. innerHTML = "Select Upload file! ";}}/*** Get the Server file Size and start to resume * @ param file * @ param I */function uploadFileInit (file, I) {if (file) {var startSize = 0; var endSize = 0; var date = file. lastModifiedDate; var lastModifyTime = date. getFullYear () + "-" + (date. getMonth () + 1) + "-" + date. getDate () + "-" + date. getHours () + "-" + date. getMinutes () + "-" + date. getSeconds () // get the size of the current file that has been uploaded jQuery. post ("xxx/getChunkedFileSize. do ", {" fileName ": encodeURIComponent (File. name), "fileSize": file. size, "lastModifyTime": lastModifyTime, "chunkedFileSize": "chunkedFileSize"}, function (data) {if (data! =-1) {endSize = Number (data);} uploadFile (file, startSize, endSize, I );});}} /*** multipart Upload file */function uploadFile (file, startSize, endSize, I) {var date = file. lastModifiedDate; var lastModifyTime = date. getFullYear () + "-" + (date. getMonth () + 1) + "-" + date. getDate () + "-" + date. getHours () + "-" + date. getMinutes () + "-" + date. getSeconds () var reader = new FileReader (); reader. onload = function loaded (evt) {// construct XML HttpRequest object, which sends the file Binary data var xhr = new XMLHttpRequest (); xhr. sendAsBinary = function (text) {var data = new ArrayBuffer (text. length); var ui8a = new Uint8Array (data, 0); for (var I = 0; I <text. length; I ++) ui8a [I] = (text. charCodeAt (I) & 0xff); this. send (ui8a);} xhr. onreadystatechange = function () {if (xhr. readyState = 4) {// indicates that the code of the server is 200. if (xhr. status = 200) {// Method for accepting plain text data var message = Xhr. responseText; message = Number (message); uploadProgress (file, startSize, message, I);} else {msg. innerHTML = "Upload error, server error! ";}}; // Create callback method xhr. open (" POST "," xxx/appendUpload2Server. do? FileName = "+ encodeURIComponent (file. name) + "& fileSize =" + file. size + "& lastModifyTime =" + lastModifyTime, false); xhr. overrideMimeType ("application/octet-stream; charset = UTF-8"); xhr.sendAsBinary(evt.tar get. result) ;}; if (endSize <file. size) {// process the file Sending (byte) startSize = endSize; if (paragraph> (file. size-endSize) {endSize = file. size;} else {endSize + = paragraph;} if (file. webkitSlice) {// webkit browser blob = file. webkitSlice (startSize, endSize);} else blob = file. slice (startSize, endSize); reader. readAsBinaryString (blob);} else {document. getElementById ('ssssnumber' + I ). innerHTML = '000000'; }}// display the processing process function uploadProgress (file, startSize, uploadLen, I) {var percentComplete = Math. round (uploadLen * 100/file. size); document. getElementById ('ssssnumber' + I ). innerHTML = percentComplete. toString () + '%'; // if (uploadState = 1) {uploadFile (file, startSize, uploadLen, I );}} /* pause upload */function pauseUpload () {uploadState = 2;}/*** trigger event after selecting a file */function fileSelected () {fileList = document. getElementById ('filetupload'); var length = fileList. files. length; var frame = document. getElementById ('fileframework'); for (var I = 0; I <length; I ++) {file = fileList. files [I]; if (file) {var fileSize = 0; if (file. size & gt; 1024*1024) fileSize = (Math. round (file. size * 100/(1024*1024)/100 ). toString () + 'mb'; else fileSize = (Math. round (file. size * 100/1024)/100 ). toString () + 'kb'; var nameDiv = document. createElement ("div"); nameDiv. setAttribute ("id", "fileName" + I); nameDiv. innerHTML = 'name: '+ file. name; var sizeDiv = document. createElement ("div"); sizeDiv. setAttribute ("id", "fileSize" + I); sizeDiv. innerHTML = 'filesize: '+ fileSize; var typeDiv = document. createElement ("div"); typeDiv. setAttribute ("id", "progressNumber" + I); typeDiv. innerHTML = '';} frame. appendChild (nameDiv); frame. appendChild (sizeDiv); frame. appendChild (typeDiv );}}

 

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.