Java and WebUploader combined to achieve file upload function of instance code
- 2020-06-15 09:05:35
- OfStack
I also encountered the problem of file uploading when I was writing a small project before, but I did not find a good solution. Although we've seen WebUploader before in our search for various solutions, we haven't taken a step further. I'm going to dig a little bit deeper this time, and I'll just summarize it here.
Simple files and normal data are uploaded and saved
jsp page:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/FileUploadServlet" method="post" enctype="multipart/form-data">
File: <input type="file" value=" Please select file " name="file" /> <br/>
Information: <input type="text" name="info" /> <br/>
<input type="submit" value=" submit " />
</form>
</body>
</html>
servlet:
package com.yihengliu.web.action;
import java.io.File;
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;
import org.apache.commons.io.FileUtils;
/**
* Servlet user to accept file upload
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String serverPath = "e:/";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println(" Into the background ...");
// 1. create DiskFileItemFactory Object to configure the cache
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 2. create ServletFileUpload object
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 3. Sets the file name encoding
servletFileUpload.setHeaderEncoding("utf-8");
// 4. Start parsing the file
try {
List<FileItem> items = servletFileUpload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) { // >> Common data
String info = fileItem.getString("utf-8");
System.out.println("info:" + info);
} else { // >> file
// 1. Get file name
String name = fileItem.getName();
// 2. Gets the actual contents of the file
InputStream is = fileItem.getInputStream();
// 3. Save the file
FileUtils.copyInputStreamToFile(is, new File(serverPath + "/" + name));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
Upload using the WebUploader component
Sharding, concurrency, preview, compression, multi - way to add folders (file multi - selection, drag and so on), wonderful transmission
Page style use
<html>
<title> use webuploader upload </title>
<!-- 1. The introduction of the file -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/js/webuploader.css" rel="external nofollow" >
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/webuploader.js"></script>
</head>
<body>
<!-- 2. Create page elements -->
<div id="upload">
<div id="filePicker"> File upload </div>
</div>
<!-- 3. add js code -->
<script type="text/javascript">
var uploader = WebUploader.create(
{
swf:"${pageContext.request.contextPath }/js/Uploader.swf",
server:"${pageContext.request.contextPath }/FileUploadServlet",
pick:"#filePicker",
auto:true
}
);
</script>
</body>
</html>
Generate filename list, display upload progress in real time, display thumbnail
Add file list div,
<div id="fileList"></div>
Generate thumbnails and display upload progress
// Generate thumbnails and upload progress
uploader.on("fileQueued", function(file) {
// Appends the file information to fileList the div In the
$("#fileList").append("<div id='" + file.id + "'><img/><span>" + file.name + "</span><div><span class='percentage'><span></div></div>")
// Make thumbnails
// error : Not a picture, yes error
// src: Represents the address where the thumbnail image was generated
uploader.makeThumb(file, function(error, src) {
if (error) {
$("#" + file.id).find("img").replaceWith("<span> Unable to preview </span>");
} else {
$("#" + file.id).find("img").attr("src", src);
}
});
}
);
// Monitor upload progress
// percentage: Represents the percentage of files uploaded
uploader.on("uploadProgress", function(file, percentage) {
$("#" + file.id).find("span.percentage").text(Math.round(percentage * 100) + "%");
});
Drag and drop upload, paste upload
Create the drag and drop area and set the style:
<style type="text/css">
#dndArea {
width: 200px;
height: 100px;
border-color: red;
border-style: dashed;
}
</style>
<!-- Create an area for drag and drop -->
<div id="dndArea"></div>
Add dnd area configuration to base configuration (enable drag and drop)
Masking responses outside the drag and drop area
Turn on paste
var uploader = WebUploader.create(
{ swf:"${pageContext.request.contextPath }/js/Uploader.swf",
server:"${pageContext.request.contextPath }/FileUploadServlet",
pick:"#filePicker",
auto:true,
// Open the drag and drop
dnd:"#dndArea",
// Masking responses outside the drag and drop area
disableGlobalDnd:true,
//
}
);
Block uploads of files
The front-end generates an md5 string according to the file it needs to send to the background, which creates a folder named after the md5 string. The front end sends the file in blocks and sends the serial number of the file block to the background. After the background receives the file, it is saved by the serial number name. The front end sends after the notification background merges the file.
Front-end configuration, whether to open block, block size, number of threads, etc
// Upload basic configuration
var uploader = WebUploader.create(
{
swf:"${pageContext.request.contextPath }/js/Uploader.swf",
server:"${pageContext.request.contextPath }/FileUploadServlet",
pick:"#filePicker",
auto:true,
dnd:"#dndArea",
disableGlobalDnd:true,
paste:"#uploader",
// Block upload Settings
// Whether the block
chunked:true,
// Per file size (default 5M )
chunkSize:5*1024*1024,
// Starting several threads is not the default 3 A)
threads:3,
// When uploading the current file, be ready 1 A file
prepareNextFile:true
}
);
Front-end monitoring blocks
It can be divided into three time points:
before-send-file: This method is called before a file is uploaded (it is only called before 1 file is uploaded).In this method, you get the md5 string of the file as the directory name to hold the partitioned file in the background
before-send: This method is called before each block file is uploaded (each block is called before uploading).In this method, you can send the md5 string to the background, which determines whether there is already a chunking function to send to reach the breakpoint
after-send-file: This method is called after all file uploads have completed without errors (called after all block uploads have completed).In this method, you can notify the background to merge all the blocks
The front-end gets the file md5 string and sends each block to the background. The background receives the file sent by blocks if no folder is created
// Listen for the time at which blocks are uploaded, and continue at breakpoint
var fileMd5;
WebUploader.Uploader.register({
"before-send-file":"beforeSendFile",
"before-send":"beforeSend",
"after-send-file":"afterSendFile"
},{
beforeSendFile:function(file) {
// create 1 a deffered, Used to notify if the operation is complete
var deferred = WebUploader.Deferred();
// Compute file only 1 Identity, used for breakpoint continuation and masterpass
(new WebUploader.Uploader()).md5File(file, 0, 5*1024*1024)
.progress(function(percentage){
$("#"+file.id).find("span.state").text(" Retrieving file information ...");
})
.then(function(val) {
fileMd5 = val;
$("#" + file.id).find("span.state").text(" File information was obtained successfully ");
// release
deferred.resolve();
});
// Notify completion
return deferred.promise();
},
beforeSend:function() {
var deferred = WebUploader.Deferred();
// Send a file md5 String to background
this.owner.options.formData.fileMd5 = fileMd5;
deferred.resolve();
return deferred.promise();
},
afterSendFile:function() {
}
}
);
Add the state tag
$("#fileList").append("<div id='" + file.id + "'><img/><span>" + file.name + "</span><div><span class='state'></span></div><div><span class='percentage'></span></div></div>");
Save the file
// 4. Start parsing the file
// file md5 Retrieved string
String fileMd5 = null;
// Index of files
String chunk = null;
try {
List<FileItem> items = servletFileUpload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) { // >> Common data
String fieldName = fileItem.getFieldName();
if ("info".equals(fieldName)) {
String info = fileItem.getString("utf-8");
System.out.println("info:" + info);
}
if ("fileMd5".equals(fieldName)) {
fileMd5 = fileItem.getString("utf-8");
System.out.println("fileMd5:" + fileMd5);
}
if ("chunk".equals(fieldName)) {
chunk = fileItem.getString("utf-8");
System.out.println("chunk:" + chunk);
}
} else { // >> file
/*// 1. Get file name
String name = fileItem.getName();
// 2. Gets the actual contents of the file
InputStream is = fileItem.getInputStream();
// 3. Save the file
FileUtils.copyInputStreamToFile(is, new File(serverPath + "/" + name));*/
// If the folder does not create the folder
File file = new File(serverPath + "/" + fileMd5);
if (!file.exists()) {
file.mkdirs();
}
// Save the file
File chunkFile = new File(serverPath + "/" + fileMd5 + "/" + chunk);
FileUtils.copyInputStreamToFile(fileItem.getInputStream(), chunkFile);
}
}
The front end notifies action to merge the files
Front-end added:
package com.yihengliu.web.action;
import java.io.File;
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;
import org.apache.commons.io.FileUtils;
/**
* Servlet user to accept file upload
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String serverPath = "e:/";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println(" Into the background ...");
// 1. create DiskFileItemFactory Object to configure the cache
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 2. create ServletFileUpload object
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 3. Sets the file name encoding
servletFileUpload.setHeaderEncoding("utf-8");
// 4. Start parsing the file
try {
List<FileItem> items = servletFileUpload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) { // >> Common data
String info = fileItem.getString("utf-8");
System.out.println("info:" + info);
} else { // >> file
// 1. Get file name
String name = fileItem.getName();
// 2. Gets the actual contents of the file
InputStream is = fileItem.getInputStream();
// 3. Save the file
FileUtils.copyInputStreamToFile(is, new File(serverPath + "/" + name));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
0
New merge action:
package com.yihengliu.web.action;
import java.io.File;
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;
import org.apache.commons.io.FileUtils;
/**
* Servlet user to accept file upload
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String serverPath = "e:/";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println(" Into the background ...");
// 1. create DiskFileItemFactory Object to configure the cache
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 2. create ServletFileUpload object
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 3. Sets the file name encoding
servletFileUpload.setHeaderEncoding("utf-8");
// 4. Start parsing the file
try {
List<FileItem> items = servletFileUpload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) { // >> Common data
String info = fileItem.getString("utf-8");
System.out.println("info:" + info);
} else { // >> file
// 1. Get file name
String name = fileItem.getName();
// 2. Gets the actual contents of the file
InputStream is = fileItem.getInputStream();
// 3. Save the file
FileUtils.copyInputStreamToFile(is, new File(serverPath + "/" + name));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
1
Breakpoint continuingly
Add a check before the front-end page is sent to check whether the blocks have been uploaded
package com.yihengliu.web.action;
import java.io.File;
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;
import org.apache.commons.io.FileUtils;
/**
* Servlet user to accept file upload
*/
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String serverPath = "e:/";
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getWriter().append("Served at: ").append(request.getContextPath());
System.out.println(" Into the background ...");
// 1. create DiskFileItemFactory Object to configure the cache
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 2. create ServletFileUpload object
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
// 3. Sets the file name encoding
servletFileUpload.setHeaderEncoding("utf-8");
// 4. Start parsing the file
try {
List<FileItem> items = servletFileUpload.parseRequest(request);
for (FileItem fileItem : items) {
if (fileItem.isFormField()) { // >> Common data
String info = fileItem.getString("utf-8");
System.out.println("info:" + info);
} else { // >> file
// 1. Get file name
String name = fileItem.getName();
// 2. Gets the actual contents of the file
InputStream is = fileItem.getInputStream();
// 3. Save the file
FileUtils.copyInputStreamToFile(is, new File(serverPath + "/" + name));
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
2
Add validation to action
else if ("checkChunk".equals(action)) {
// Verify that the file has been uploaded and returns the results to the front end
// The file only 1 said
String fileMd5 = request.getParameter("fileMd5");
// Current block subscript
String chunk = request.getParameter("chunk");
// Current block size
String chunkSize = request.getParameter("chunkSize");
// Find the chunked file
File checkFile = new File(serverPath + "/" + fileMd5 + "/" + chunk);
// Check if the file exists and size 1 to
response.setContentType("text/html;charset=utf-8");
if (checkFile.exists() && checkFile.length() == Integer.parseInt((chunkSize))) {
response.getWriter().write("{\"ifExist\":1}");
} else {
response.getWriter().write("{\"ifExist\":0}");
}
}