Fineuploader Use Experience __fineuploader

Source: Internet
Author: User
Tags documentation

Recently do a need to have an attachment management bulletin board, so found this fineuploader, pure JavaScript implementation, Ajax way, upload files do not refresh the page , do not rely on any Third-party library, very easy to use. But at the beginning of the use of Google a lot of information, including official documents and demo. Found that a lot of information on the Internet is either very old, or the reference to me is not very important. To the completion of this function, write down their own experience, to leave some records, if it can be a little reference value for others is better.

Fineuploader Official website: http://fineuploader.com/, packaged JS is to charge, the price is not cheap.

Open Source project: Https://github.com/FineUploader/fine-uploader

The fineuploader used in this article have been uploaded to http://download.csdn.net/detail/jxiaoliu/8071341 (streamlined, stripped of all files that are not available, including templates). Code required for Fineuploader

First of all, the introduction of the necessary JS file and CSS

<link href= "<%=request.getcontextpath ()%>/fineuploader5/fineuploader-5.0.2.css" rel= "stylesheet"/>
<script src= "<%=request.getcontextpath ()%>/fineuploader5/fineuploader-5.0.2.js" type= "text/ JavaScript "></script>
OK, just the two files.

Next, you can instantiate this uploader in JS:

var submitfile = false;//is used to control the submit file var uploader = null only when the submit button is pressed; function Createuploader () {uploader = new QQ. Fineuploader ({element:document.getElementById (' Fine-uploader '), Autoupload:false, request: {ENDP Oint: ' <%=request.getcontextpath ()%>/updownfile/uploadfile?op=add '}, session: {endpoint:
	      	' <%=request.getcontextpath ()%>/manage/bulletin?op=getattach ', params: {' id ': ${bulletin.id}}}, DeleteFile: {enabled:true, endpoint: ' <%=request.getcontextpath ()%>/manage/bulletin?op=del ' , method: ' POST ', Forceconfirm:true, Confirmmessage: ' Are you sure you want to delete the file {filename}? Not recoverable. ', Deletingfailedtext: ' Delete failed.   '}, Editfilename: {enabled:false}, callbacks: {onallcomplete:
	      		function (Successids, failids) {if (submitfile) SubmitData (successids);
}
	      	}
	}); }
You must do this when the page is initialized, and continue to add the following sentence:

Window.onload = Createuploader;
Fineuploader must be instantiated into a "container" in an HTML page, typically a <div> element, and the first option "element" indicates the corresponding HTML element. So the following elements must exist on the page:

<div id= "Fine-uploader" ></div>
In addition, because Fineuploader is divided into core and UI two categories, where the core should be users completely customized to their own JS program to go, need to write their own user interface. For beginners or general users, you can directly use the template provided by Fineuploader (template, users can download the Open source project), this is the direct copy of the template file (default.html) in the corresponding code snippet to the current HTML page anywhere:

<script type= "Text/template" id= "qq-template" > <div class= "qq-uploader-selector qq-uploader" > <div cl ass= "Qq-upload-button-selector Qq-upload-button" > <div> upload accessories </div> </div> <ul class= " Qq-upload-list-selector qq-upload-list "> <li> <div class=" Qq-progress-bar-container-selector "
          ; <div class= "Qq-progress-bar-selector qq-progress-bar" ></div> </div> <span class= "Qq-u Pload-spinner-selector qq-upload-spinner "></span> <span class=" Qq-edit-filename-icon-selector qq-edit- Filename-icon "></span> <span class=" Qq-upload-file-selector qq-upload-file "></span> & Lt;span class= "Qq-upload-size-selector qq-upload-size" ></span> <a class= "Qq-upload-cancel-selector qq- Upload-cancel "href=" # > Discard upload </a> <a class= "Qq-upload-retry-selector qq-upload-retry" href= "#" >retry
 </a>       <a class= "Qq-upload-delete-selector qq-upload-delete" href= "#" > Delete </a> <span class= "Qq-upload -status-text-selector qq-upload-status-text "></span> </li> </ul> </div> </script >
Many documents or materials say the outermost <script> mark can not, but I test can not, must be. Where the id attribute id= "qq-template" is critical, otherwise fineuploader doesn't know where to look for its UI interface and show it.

The template's style can be modified by the Fineuploader-5.0.2.css file, which is not discussed here.

At this point, Fineuploader has been complete, of course, to run must be the background code upload support. second, the background Java code

The code for uploading files with the help of the Apache.commons.fileupload component is as follows:

try {
	Multipartuploadparser uploadparser = new Multipartuploadparser (Request, New File (System.getproperty (" Java.io.tmpdir "));
	Fileitem UploadFile = Uploadparser.getfirstfile ();
	Path file = Java.nio.file.Paths.get (Uploadfile.getname ());
	Uploadfile.write (New File (RootPath + "/temp/" + file.getfilename (). toString ()));
	Result.put ("Success", true);
} catch (Exception e) {
	result.put ("Success", false);
	Response.getwriter (). Print (result.tostring ());
	E.printstacktrace ();
}

It is important to note that after the file is uploaded successfully, a JSON-formatted object must be returned to the foreground, which must contain a "success" object with a value of true or false, representing the success or failure of the file upload.

In addition, when the user selects multiple files and uploads, it is in a multi-threaded manner independent of the same time. Each file upload success will trigger the OnComplete event in callbacks, all files upload successfully after the Onallcomplete event triggered.

The Multipartuploadparser class objects are defined as follows:

Package updownfile;
Import Org.apache.commons.fileupload.FileItem;
Import org.apache.commons.fileupload.FileUploadException;
Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;
Import Org.apache.commons.fileupload.servlet.ServletFileUpload;
Import Org.apache.commons.lang3.StringUtils;
Import Org.slf4j.Logger;

Import Org.slf4j.LoggerFactory;

Import Javax.servlet.http.HttpServletRequest;
Import Java.io.File;
Import java.io.IOException;
Import java.io.UnsupportedEncodingException;

Import java.util.*;

	public class Multipartuploadparser {final Logger log = Loggerfactory.getlogger (Multipartuploadparser.class);

	Private Map params = new HashMap ();

	Private List files = new ArrayList (); Fileitemsfactory is a field (even though it's scoped to the constructor) to prevent the//Org.apache.commons.fileuplo
	Ad.servlet.FileCleanerCleanup thread from attempting to delete the//temp file before while it is still being used. Filecleanercleanup uses a java.lang.ref.RefErencequeue to deletes the temp file when the Fileitemsfactory marker object is gced private diskfileitemfactory fileitems

	Factory; @SuppressWarnings ("unchecked") public Multipartuploadparser (HttpServletRequest request, File repository) throws  Exception {if (!repository.exists () &&!repository.mkdirs ()) {throw new IOException ("Unable to mkdirs to
		"+ Repository.getabsolutepath ());

        } fileitemsfactory = Setupfileitemfactory (repository);
        Servletfileupload upload = new Servletfileupload (fileitemsfactory);

		List Formfileitems = upload.parserequest (request);

		Parseformfields (Formfileitems); if (Files.isempty ()) {Log.warn ("No files were found when processing the requst.

			Debugging info follows. ");

			WriteDebugInfo (Request);
		throw new Fileuploadexception ("No files were found when processing the requst.");
			else {if (log.isdebugenabled ()) {writedebuginfo (request); }} private Diskfileitemfactory setupfileitemfActory (File repository) {Diskfileitemfactory factory = new Diskfileitemfactory ();
		Factory.setsizethreshold (10*1024*1024);

	Factory.setrepository (repository);
	Filecleaningtracker Ptracker = filecleanercleanup.getfilecleaningtracker (context);

		Factory.setfilecleaningtracker (Ptracker);
	return factory;
		private void WriteDebugInfo (HttpServletRequest request) {Log.debug ("--POST HEADERS-"); For (String header:Collections.list (Request.getheadernames ())) {Log.debug (' {}: {} ', header, Request.getheader (head
		ER));
		} log.debug ("--POST PARAMS--");
		For (String Key:params.keySet ()) {Log.debug ("{}: {}", key, Params.get (key));
			} private void Parseformfields (List items) throws Unsupportedencodingexception {for (Fileitem item:items) {
				if (Item.isformfield ()) {String key = Item.getfieldname ();
				String value = item.getstring ("UTF-8"); if (Stringutils.isnotblank (key)) {Params.put (key), stringutils.defaultstring (Value));
			} else {Files.add (item);
	}} public Map Getparams () {return params;
		Public List GetFiles () {if (Files.isempty ()) {throw new RuntimeException ("No fileitems exist.");
	return to files;
		Public Fileitem GetFirstFile () {if (Files.isempty ()) {throw new RuntimeException ("No fileitems exist.");
	Return Files.iterator (). Next ();
 }
}

Three, the meaning of each option in the codeBelow is a little more detailed description of the options used by the component to make it easier for you to change according to your own project needs. Autoupload options: Control whether the user selects files immediately automatically upload the selected files, the default is true, that is, automatically uploaded to the server after the upload, will display the file name, file size and a "delete" link (delete upload file explanation see DeleteFile option). This sets the value to False, indicating that only files are listed after the user selects the file (a "Discard" link appears to the right of the file name, the link removes the corresponding file), and is uploaded manually via the Uploadstoredfiles () method when needed. Multiple option: The default is true, users can select multiple files at once and upload them. Request option: Background to accept the file upload URL path. Set the Endpoint property. Editfilename options: Set whether the file name can be modified to upload (I test as if I did not find any effect ~ ~) callbacks Option: callback function, you can monitor various events. Please refer to the official documentation for details. DeleteFile option: Used to delete files that have been uploaded. Files that can be deleted must be uploaded successfully on the same page, or a list of files initialized by the session option. The important sub options are explained as follows:
Endpoint: Background is used to delete the URL address of the file. The return value must contain the "success" property as it was uploaded
Method: Important, must be set to ' post '
Forceconfirm: Whether the Delete confirmation dialog box appears, and the default value is false session option: This option determines the list of files that need to be initialized when the control is initialized. If you do not set the item, the list of files is empty when the control is initialized. If you need to give a list of files that the user has previously uploaded, you must set the value of its child option endpoint to return the file list from the background. The values returned in the background must be in a JSON-formatted array, and each array object is a JSON-formatted object and must contain the "name" and "UUID" two attributes to specify the filename and the file's unique code name, respectively. Refer to the official documentation. Note that if the Onallcomplete event was previously defined, each file triggers the Onallcomplete event when the list of files is initialized, because each file state that is initialized is Qq.status.UPLOAD_SUCCESSFUL. That is, the flag has been uploaded successfully. So the code at the beginning of this article defines a submitfile variable and sets its initial value to false to determine whether the user submits the upload file manually or the page is initialized, and in the absence of such a decision, the codes in the Onallcomplete event are executed repeatedly.
Four, a few simple sample picture

1. Files have been selected for upload:


2. File Upload process:
3. File Upload success:

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.