First throw out the address, http://fex-team.github.io/webuploader/
There is a relatively complete demo case document. This article mainly adds a large number of comments based on file upload and image upload, which basically ensures that each line of code has comments to help understand. It is an enhanced version of the official website demo. I hope it can help everyone better understand the plug-in.
First, file upload
jQuery(function() { var $ = jQuery, $list = $('#thelist'), $btn = $('#ctlBtn'), state = 'pending', uploader; // Initialization, you can actually directly access Webuploader.upLoader uploader = WebUploader.create({ // Uncompressed image resize: false, // swf file path swf: BASE_URL + '/js/Uploader.swf', // Send to the background code for processing and save to the server server: 'http://webuploader.duapp.com/server/fileupload.php', // Select the button to select the file. Optional. // Create internally according to the current run, which may be an input element or flash.pick: '#picker' }); // Add an event by uploader. When the file is added to the queue, uploader.on( 'fileQueued', function( file ) { //When joining the queue, create a style for subsequent uploading to fail, etc., define a *p to point to the event style $list.append( '<div id="' + file.id + '">' + '<h4>' + file.name + '</h4>' + '<p>wait for upload...</p>' + '</div>' ); }); // The file is triggered during uploading, carrying the upload progress. The file represents the uploaded file. The percentage represents the uploaded progress uploader.on( 'uploadProgress', function( file, percentage ) { //Define a variable name creation progress module var $li = $( '#'+file.id ), //Find the class progress under $li, and define it as $percent------Why first look for creating $percent = $li.find('.progress .progress-bar'); //If $percent has no value, create a progress bar and add it to the corresponding file name to avoid repeated creation if ( !$percent.length ) { $percent = $('<div>' + '<div role="progressbar">' + '</div>' + '</div>').appendTo( $li ).find('.progress-bar'); } //Add pop-up text $li.find('p.state').text('uploading'); //Create a percentage of read bars for the progress module $percent.css( 'width', percentage * 100 + '%' ); }); //Uploader triggers an event, and calls this event when uploading successfully uploader uploader.on( 'uploadSuccess', function( file ) { //The event triggered when the file is added, findstate, and add the text as $( '#'+file.id ).find('p.state').text('uploaded'); }); //The uploader triggers the event, which triggers the event when the upload fails uploader.on( 'uploadError', function( file ) { //The event triggered when the file is added, findstate, and adds the text as upload error $( '#'+file.id ).find('p.state').text('upload error'); }); //This event indicates that the event will be triggered regardless of whether the upload is successful or failed uploader uploader.on( 'uploadComplete', function( file ) { //Call $( '#'+file.id ).find('.progress').fadeOut(); }); //This is a special event, and all triggers will be responded to. The function of type is to record what event is currently triggering and assign the value to the state uploader.on( 'all', function( type ) { if ( type === 'startUpload' ) { state = 'uploading'; } else if ( type === 'stopUpload' ) { state = 'paused'; } else if ( type === 'uploadFinished' ) { state = 'done'; } //According to state text pop-up if ( state === 'uploading' ) { $btn.text('paused upload'); } else { $btn.text('Start upload'); } }); //Freeze when the button is clicked, uploading starts according to the status or pause $btn.on( 'click', function() { if ( state === 'uploading' ) { uploader.stop(); } else { uploader.upload(); } });});Then upload the picture
jQuery(function() { // Assign jquery to a global variable var $ = jQuery, $list = $('#fileList'), // Optimize retina, under retina, this value is 2, the device pixel ratio ratio ratio = window.devicePixelRatio || 1, // Thumbnail size thumbnailWidth = 100 * ratio, thumbnailHeight = 100 * ratio, // Web Uploader instance uploader; // Initialize Web Uploader uploader = WebUploader.create({ // Automatic upload. auto: true, // swf file path swf: BASE_URL + '/js/Uploader.swf', // File receiving server. Call the code and save the image on the server server: 'http://webuploader.duapp.com/server/fileupload.php', // Select the file button. Optional. // Create internally according to the current run, which may be an input element or flash. pick: '#filePicker', // Only files are allowed, optional. accept: { title: 'Images', extensions: 'gif,jpg,jpeg,bmp,png', mimeTypes: 'image/*' } }); // This event is triggered when a file is added uploader.on( 'fileQueued', function( file ) { //Define the variable li var $li = $( //Create an id '<div id="' + file.id + '">' + '<img>' + //Create a class for info '<div>' + file.name + '</div>' + '</div>' ), $img = $li.find('img'); //Add the defined li to list $list.append( $li ); //Create a thumbnail, this process is asynchronous and needs to be passed in callBack(function( error, src )), usually called this method after the image is added to the queue to enhance interactivity //callback has two parameters. When error is called, src stores the address of the thumbnail uploader.makeThumb( file, function( error, src ) { if ( error ) { $img.replaceWith('<span>cannot preview</span>'); return; } $img.attr( 'src', src ); }, thumbnailWidth, thumbnailHeight ); }); // Create a progress bar to display in real time during file upload. uploader.on( 'uploadProgress', function( file, percentage ) { var $li = $( '#'+file.id ), $percent = $li.find('.progress span'); // Avoid repeated creation if ( !$percent.length ) { $percent = $('<p><span></span></p>') .appendTo( $li ) .find('span'); } $percent.css( 'width', percentage * 100 + '%' ); }); // The file is uploaded successfully, add a successful class to the item, and mark the upload success with style. uploader.on( 'uploadSuccess', function( file ) { $( '#'+file.id ).addClass('upload-state-done'); }); // File upload failed, and there was an error in reality uploading. uploader.on( 'uploadError', function( file ) { var $li = $( '#'+file.id ), $error = $li.find('div.error'); // Avoid repeated creation if ( !$error.length ) { $error = $('<div></div>').appendTo( $li ); } $error.text('upload failed'); }); // After the upload is completed, it is successful or failed, delete the progress bar first. uploader.on( 'uploadComplete', function( file ) { $( '#'+file.id ).find('.progress').remove(); });Below is the Java background code, used to obtain uploaded files and write the real path of the uploaded files to the server
1. First of all, we should create a storage location for the uploaded files. The general location is divided into temporary and real folders. Then we need to obtain the absolute paths of these two folders. In the servlet, we can do this.
ServletContext application = this.getServletContext(); String tempDirectory = application.getRealPath(Constant.TEMP_DIRECTORY) + "/"; String realDirectory = application.getRealPath(Constant.REAL_DIRECTORY) + "/";
Then create a file factory, that is, a warehouse, a parameter indicates how big it is to store flush.
The code copy is as follows: FileItemFactory factory = new DiskFileItemFactory(Constant.SIZE_THRESHOLD,new File(tempDirectory));
ServletFileUpload upload = new ServletFileUpload(factory);
2. Set up the uploaded files
upload.setSizeMax(500*1024*1024);//Set the maximum value of this upload to 500M3, parse the request body, get the upload file, and write the real path without throwing an exception
List<FileItem> list = upload.parseRequest(request); Iterator<FileItem> iter = list.iterator(); while (iter.hasNext()) { FileItem item = iter.next(); //item.isFormField() is used to determine whether the current object is the data of the file form field. If the return value is true, it means that it is not a normal form field if(item.isFormField()){ System.out.println( "Normal form field" +item.getFieldName()); System.out.println(item.getString("utf-8")); }else{ //System.out.println("file form field" + item.getFieldName()); /* * Only the file form field writes the contents in the object to the real folder*/ String lastpath = item.getName();//Get the name of the uploaded file lastpath = lastpath.substring(lastpath.lastIndexOf(".")); String filename = UUID.randomUUID().toString().replace("-", "") + lastpath; item.write(new File(realDirectory+filename)); package com.lanyou.support.servlet;import java.io.File;import java.io.IOException;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.commons.logging.LogFactory;import org.apache.struts2.ServletActionContext;public class FileUpload extends HttpServlet { private static final long serialVersionUID = 1L; private static Log logger = LogFactory.getLog(FileUpload.class); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Upload file with type 1 event 2apk String t = req.getParameter("t") == null ? "1" : req.getParameter("t") .trim(); String path = ""; JSONObject ob = new JSONObject(); try { //Task to encapsulate each item in the request message into a separate DiskFileItem object//Save it in memory when the uploaded file items are small, and save it in the disk when the disk is zero.//Create a file warehouse (factory) FileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload servletFileUpload = new ServletFileUpload(factory); //Set the uploaded file servletFileUpload.setSizeMax(1024 * 1024 * 2);// Maximum 2M data servletFileUpload.setFileSizeMax(2 * 1024 * 1024); servletFileUpload.setHeaderEncoding("UTF-8");// Solve the problem of garbled file name//Solve the request body, get the uploaded file, and write the real path if no exception is thrown//Get the file list according to the request List<FileItem> fileItemsList = servletFileUpload.parseRequest(req); //Fetch a separate file object from the file list for (FileItem item : fileItemsList) { //Defend whether the file is an ordinary form type, where the file type enters the judgment if (!item.isFormField()) { //If the uploaded file is greater than the specified size, return if (item.getSize() > 2 * 1024 * 1024) { return; } // System.out.println("The size of the uploaded file: "+item.getSize()); // System.out.println("Upload file type: "+item.getContentType()); // System.out.println("Upload file name: "+item.getName()); //Upload file name String fileName = item.getName(); String ent = ""; //Content type if (item.getContentType().equalsIgnoreCase("image/x-png") || item.getContentType().equalsIgnoreCase( "image/png")) { ent = ".png"; } else if (item.getContentType().equalsIgnoreCase( "image/gif")) { ent = ".gif"; } else if (item.getContentType().equalsIgnoreCase( "image/bmp")) { ent = ".bmp"; } else if (item.getContentType().equalsIgnoreCase( "image/pjpeg") || item.getContentType().equalsIgnoreCase( "image/jpeg")) { ent = ".jpg"; } //What format is the obtaining the file if (fileName.lastIndexOf(".") != -1) { ent = fileName.substring(fileName.lastIndexOf(".")); } fileName = "ev_" + System.currentTimeMillis() + ent; // Define the file path, depending on your folder structure, you may need to make changes if (t.equals("1")) { path = "upload/ev/" + fileName; } else { path = "upload/pk/" + fileName; } // Save the file to the server File file = new File(req.getSession().getServletContext() .getRealPath(path)); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } item.write(file); // logger.info(path); // break; ob.accumulate("url", path); } } resp.setContentType("text/html; charset=UTF-8"); resp.getWriter().write(ob.toString()); } catch (Exception e) { e.printStackTrace(); } finally { // Response client // resp.setContentType("text/html; charset=UTF-8"); // resp.getWriter().write(ob.toString()); } }}The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.