_javascript technique of File upload JS plugin based on Webuploader

Source: Internet
Author: User
Tags constant throw exception

First, get rid of the address,http://fex-team.github.io/webuploader/ .

There is a more complete demo case document, this article is mainly based on file upload and image upload added a lot of comments, basically ensure that each line of code have comments to help understand, is the official website demo of the enhanced version, hope to help you better understand the plug-in

First, file upload.

jquery (function () {var $ = jquery, $list = $ (' #thelist '), $btn = $ (' #ctlBtn '), state = ' pending ', uploader; Initialized, you can actually directly access webuploader.uploader UpLoader = webuploader.create ({//uncompressed image resize:false,//swf file path swf:b

  Ase_url + '/js/uploader.swf ',//Send to background code for processing, save to server: ' http://webuploader.duapp.com/server/fileupload.php ', Select the button for the file.
  Optional.
  The interior is created according to the current run, possibly an INPUT element, or it may be flash.

 Pick: ' #picker '}); Uploader adds an event that triggers the Uploader.on (' filequeued ', function (file) {//When joining the queue, creates a style for subsequent upload success failure, etc.) when the file is added to the queue, defining a * P indicates $list. Append (' <div id= ' + file.id + ' "class=" item "> ' + ' 

  then picture upload

jquery (function () {//To assign jquery to a global variable var $ = jquery, $list = $ (' #fileList '),//optimize retina, under Retina This value is 2, device pixel ratio Ratio = Window.devicepixelratio | |

 1,//thumbnail size Thumbnailwidth = ratio, Thumbnailheight = ratio,//Web uploader instance uploader;
  Initialize Web Uploader Uploader = webuploader.create ({//automatically uploaded. Auto:true,//swf file path Swf:base_url + '/js/uploader.swf ',//File receive server. Call code, save the picture on server side: ' http://webuploader.duapp.com/server/fileupload.php ',//Select File button.
  Optional.
  The interior is created according to the current run, possibly an INPUT element, or it may be flash.
  Pick: ' #filePicker ',//Only allow selection of files, optional.

 Accept: {title: ' Images ', Extensions: ' Gif,jpg,jpeg,bmp,png ', mimetypes: ' image/* '}} Triggers this event when a file is added Uploader.on (' filequeued ', function (file) {//define variable li var $li = $ (//Create an ID ' <div id= ')  + file.id + ' "class=" File-item thumbnail "> ' + '  '
   + file.name + ' </div> ' + ' </div> ' ), $img = $li. Find (' img ');

  Add the defined Li to the list $list. Append ($li); Create thumbnails, this procedure is asynchronous, need to pass in callback (function (error, SRC)), usually call this method after the picture joins the queue to enhance interactivity//callback has two parameters, call error when it fails, SRC holds the address of the thumbnail uploader.makethumb (file, function (Error, SRC) {if (error) {$img. replacewith (' <span> not pre
    </span> ');
   Return
  $img. attr (' src ', src);
 }, Thumbnailwidth, thumbnailheight);

 });
 The file upload process creates a progress bar to display in real time. Uploader.on (' uploadprogress ', function (file, percentage) {var $li = $ (' # ' +file.id), $percent = $li. Find ('. progr

  ESS span ');
     Avoid duplicating the IF (! $percent. length) {$percent = $ (' <p class= ' progress ' ><span></span></p> ')
  . Appendto ($li). Find (' span ');
 $percent. css (' width ', percentage * 100 + '% ');

 });
 File upload Success, add success class to item, upload success with style tag.
 Uploader.on (' uploadsuccess ', function (file) {$ (' # ' +file.id). addclass (' Upload-state-done ');

 });
 File upload failed, reality upload error. Uploader.on (' Uploaderror ', function (file) {var $li = $ (' # ' +file.id), $error = $li. Find (' div.error ');
  Avoid duplicating the IF (! $error. length) {$error = $ (' <div class= ' error ' ></div> '). Appendto ($li);
 $error. Text (' upload failed ');

 });
 Finished uploading, success or failure, first delete the progress bar.
 Uploader.on (' uploadcomplete ', function (file) {$ (' # ' +file.id). Find ('. Progress '). Remove ();
});

 });

Here is the Java background code to get the uploaded file and write the actual path of the uploaded file to the server

1. First, we should build a storage location for uploaded files, the general location is divided into temporary and really folder, then we need to get the absolute path of these two folders, in the servlet we can do

 ServletContext application = This.getservletcontext ();
 String tempdirectory = Application.getrealpath (constant.temp_directory) + "/";
 String realdirectory = Application.getrealpath (constant.real_directory) + "/";

Then set up a file factory that is the warehouse a parameter indicating how big the store is after flush,

Copy Code code as follows:
Fileitemfactory factory = new Diskfileitemfactory (constant.size_threshold,new File (tempdirectory));
Servletfileupload upload = new Servletfileupload (factory);

2. To upload the file to set

Upload.setsizemax (500*1024*1024)//Set the maximum upload value is 500m3,. Parse request body, get upload file, do not throw exception write True path

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 data for a file form field if the return value is true it is not the normal form field if
 (Item.isformfield ()) {
  System.out.println ("Plain 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 will write the contents of the object to the real folder/*
  Lastpath = Item.getname (), or 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.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, Ioexcepti On {//Type 1 event upload file 2apk String t = req.getparameter ("t") = = null?
 "1": Req.getparameter ("T"). Trim ();
 String path = "";
 Jsonobject ob = new Jsonobject ();  try {///to encapsulate each item in the request message as a task for a separate Diskfileitem object//When the uploaded file item is saved in memory for a relatively large amount of time, save it in a disk-zero folder/set up a file warehouse (factory) Fileitemfactory factory
 = new Diskfileitemfactory ();
 Servletfileupload servletfileupload = new Servletfileupload (factory);

 Set the uploaded file Servletfileupload.setsizemax (1024 * 1024 * 2);//MAX 2M Data Servletfileupload.setfilesizemax (2 * 1024 * 1024); Servletfileupload.setheaderencoding ("UTF-8"); Resolve file name garbled problem//Resolution request body, get upload file, do not throw exception to write real path///Get file list according to request List<filei
 tem> fileitemslist = servletfileupload.parserequest (req); Remove a separate file object from the file list for (Fileitem item:fileitemslist) {//To determine if the file is a normal form type, where file type entry is judged if (!item.isformfield ()) {//AS The uploaded file is larger than the specified size then return if (Item.getsize () > 2 * 10* 1024) {return;
 }//System.out.println ("Upload file Size:" +item.getsize ());
 System.out.println ("Type of File uploaded:" +item.getcontenttype ());
 
 
 System.out.println ("The name of the uploaded file:" +item.getname ());

 The name of the upload file String fileName = Item.getname ();
 String ent = ""; The type of content 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/j
 Peg ")) {ent =". jpg ";
 //Get the file is that format if (Filename.lastindexof (".")!=-1) {ent = filename.substring (Filename.lastindexof ("."));
 FileName = "Ev_" + system.currenttimemillis () + ent;
 Define file path, depending on your folder structure, may need to be modified if (T.equals ("1")) {path = "upload/ev/" + fileName; else {path = "upload/pk/" + FileName;
 //Save files to server 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 the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.