Based on html5+ Java to achieve large file upload instance code

  • 2020-04-01 04:35:43
  • OfStack

Nonsense not to say, directly to everyone posted code, specific code as follows:

The HTML code is as follows:


<body>
<input id="fileid" type="file" accept="video/*;capture=camera"
onchange="onfile(this)">
<input id="btn" type="button" value=" submit ">
<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 data stream ends ");
if(xhr.status == 200){
var infor = xhr.responseText;
alert(" Server-side response  = "+infor);
}
}
}
</script>
</body>

The Java code is as follows:


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 the uploaded file, and store the uploaded file in the web-inf directory, without allowing direct access to the outside world, so as to ensure the security of the uploaded file
String savePath = this.getServletContext().getRealPath(
"/WEB-INF/upload");
File file = new File(savePath);
System.out.println("test . ");
//Determines if the save directory for the uploaded file exists
if (!file.exists() && !file.isDirectory()) {
System.out.println(savePath + " The directory does not exist and needs to be created ");
//Create a directory
file.mkdir();
}
//Message prompt
String message = "";
try {
//Process file upload steps using the Apache file upload component:
//1. Create a DiskFileItemFactory factory
DiskFileItemFactory factory = new DiskFileItemFactory();
//2. Create a file upload parser
ServletFileUpload upload = new ServletFileUpload(factory);
//Resolve the file name of the upload Chinese garbled code
upload.setHeaderEncoding("UTF-8");
//3. Determine whether the data submitted is the data of the uploaded form
if (!ServletFileUpload.isMultipartContent(request)) {
//Get the data the traditional way
return;
}
//4. Use the ServletFileUpload parser to parse the uploaded data, and the parse result returns a List<FileItem> Collection, each FileItem corresponds to an input item of the Form
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
//If fileitem encapsulates data for a normal input item
if (item.isFormField()) {
String name = item.getFieldName();
//Solve the problem of Chinese garbled data of common input items
String value = item.getString("UTF-8");
// value = new String(value.getBytes("iso8859-1"),"UTF-8");
System.out.println(name + "=" + value);
} else {//If fileitem encapsulates an uploaded file
//Get the name of the uploaded file,
String filename = item.getName();
System.out.println(filename);
if (filename == null || filename.trim().equals("")) {
continue;
}
//Note: file names submitted by different browsers are different. Some browsers submit file names with paths, such as:
//C :ab1.txt, and some are simply file names such as: 1.txt
//Process the path part of the filename of the obtained uploaded file, leaving only the filename part
filename = filename
.substring(filename.lastIndexOf("\") + 1);
//Gets the input stream for 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];
//An identifier that determines whether the data in the input stream has been read
int len = 0;
//The loop reads the input stream into the buffer, (len=in.read(buffer))> So 0 means that in has some data in it
while ((len = in.read(buffer)) > 0) {
//Use the FileOutputStream output stream to write buffer data to the specified directory (savePath + " ")
//+ filename)
out.write(buffer, 0, len);
}
out.flush();
//Close the input stream
in.close();
//Close the output stream
out.close();
//Deletes temporary files that are generated while processing file uploads
item.delete();
message = " File uploaded successfully! ";
}
}
} catch (Exception e) {
message = " File upload failed! ";
e.printStackTrace();
}
request.setAttribute("message", message);
request.getRequestDispatcher("/message.jsp").forward(request, response);
}
}

The Java packages used are more than 1 gb uploaded

Commons fileupload - 1.2.1 jar
Commons - IO - 1.3.2. The jar


//xhr.setRequestHeader("Content-Type","application/octet-stream;charset=UTF-8"); 
 I can't add 

Related articles: