Upload of swfupload file for Flash upload component

Source: Internet
Author: User

SWFUpload is a client file Upload tool, originally developed by Vinterwebb.se, which provides Web developers with a rich capability to transcend traditional <input type by integrating flash and JavaScript technology = File upload mode for the "file"/> tag.

Currently this project is placed in: https://code.google.com/p/swfupload/

The corresponding Chinese api:http://leeon.me/upload/other/swfupload.html

Since SWFUpload is developed in combination with Falsh and JavaScript, this may not be suitable for today's popular HTML5. and SWFUpload and official website has not been updated already. It is recommended to use another plugin plupload, this plugin will automatically detect the current browser appropriate upload mode: HTML5, Flash, Silverlight.

Main features of SWFUpload:

* Can upload multiple files at the same time;

* Ajax-like no-refresh uploads;

* Upload progress can be displayed;

* Good browser compatibility;

* Compatible with other JavaScript libraries (for example: JQuery, prototype, etc.);

* Support Flash 8 and Flash 9;

Unlike other flash-based upload tools, SWFUpload has an elegant code design that allows developers to customize the look of their browser with XHTML, CSS, and JavaScript, and provides a set of concise JavaScript events With their developers, it is easy to update the page content during file upload to create a variety of dynamic effects.

Second, the general development process

1, the introduction of the corresponding JS and CSS files.

2. Instantiate the SWFUpload object and configure the object initialization.

3, browse the Web page, open and select the file to upload.

4, the background receives the foreground transmits the file stream, carries on the processing.

5. Return the corresponding parameters in the background and make the foreground prompt.

This is an example of what I do. The effect is as follows:

Example one:

Example two:

Code for example one:

index.jsp

<%--Created by IntelliJ idea. --%><%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>

Swfuploadhandlers.js

/** * Created by Zhang on 14-2-25.  */var Queueerrorarray;var setting = {upload_url: "/upload",//Background processing program path Flash_url: "swfupload/swfupload.swf", SWF Program path file_types: "*.jpg;*.png;*.gif;*.mp4;*.wmv",//allow uploading of file types file_types_description: "Web Image",//For uploading files Description file_size_limit: "200MB",//File upload size unit default to KB file_upload_limit:0,//debug debug:false,//handler s File_dialog_start_handler:filedialogstar,//Open the Select dialog to trigger event file_queued_handler:filequeued,//Add file to upload Event triggered by queue-triggered event File_queue_error_handler:fileerror//File Join queue error File_dialog_complete_handler:filedialogcomplete         ,//File selection completed triggered event Upload_start_handler:uploadstar,//File upload triggered event upload_progress_handler:uploadprogress, Event Upload_complete_handler:uploadcomplete triggered in upload,//upload complete event triggered upload_success_handler:uploadsuccess ,//The event triggered when the upload was successful//button button_placeholder_id: "Swfplacehold", Button_text: "Please select Upload file", Button_width:270, Button_height:20, Button_cursor:SWFUpload.CURSOR.HAND, Button_window_mode:SWFUpload.WINDOW_MODE . Transparent};var swfup = new swfupload (setting);/*********************************************handler************* * * Event triggered when the file dialog box is opened */function Filedialogstar () {if (Queueerrorarray) {Queueerrorarra    y = null;        }}/** * The event triggered when the file is added to the upload queue * @param Select the uploaded file object */function filequeued (file) {var swfup = this;    Current SWFUpload instance object var listItem = "<li id= '" + file.id + "' >"; ListItem + = "File:<em>" + File.name + "</em> (" + math.round (file.size/1024) + "KB) <span id= ' Progressvalue ' &    Gt;</span> ";    ListItem + = "<div id= ' progressBar ' ><div id= ' progress ' ></div></div>";    ListItem + = "<p id= ' statue ' ></p><span id= ' cancle ' ></span></li>";    $ ("#fileList"). Append (ListItem); The cancel event of the button is $ ("li#" + file.id + "#cancle"). Click (function (e) {swfup.Cancelupload (file.id);    $ ("li#" + file.id). Remove (); });}  /** * File Join queue Error-triggered event * @param file uploaded object * @param errorCode return error code * @param msg error message */function fileerror (file, ErrorCode,    msg) {//Error queue array if (!queueerrorarray) {queueerrorarray = [];    } ErrorFile = {file:file, Code:errorcode, error: '}; Switch (errorCode) {case Swfupload.queue_error.            FILE_EXCEEDS_SIZE_LIMIT:errorFile.error = ' File size exceeded limit ';        Break Case Swfupload.queue_error.            INVALID_FILETYPE:errorFile.error = ' file type not allowed ';        Break Case Swfupload.queue_error.            QUEUE_LIMIT_EXCEEDED:errorFile.error = ' exceeds the number of files limit. ';        Break Case Swfupload.queue_error.            ZERO_BYTE_FILE:errorFile.error = ' The file you selected is empty ';        Break Case Swfupload.upload_error.            HTTP_ERROR:errorFile.error = ' Server error ';        Break Case Swfupload.upload_error. Missing_upload_url:eRrorfile.error = ' program not set Upload_url attribute ';        Break Case Swfupload.upload_error.            IO_ERROR:errorFile.error = ' An error occurred while reading or transferring the file ';        Break Case Swfupload.upload_error.            ZERO_BYTE_FILE:errorFile.error = ' file is empty file ';        Break Case Swfupload.upload_error.            SECURITY_ERROR:errorFile.error = ' upload is subject to security restrictions ';        Break Case Swfupload.upload_error.            UPLOAD_FAILED:errorFile.error = ' upload error ';        Break            Default:errorFile.error = ' Upload file error, error code: ' + ErrorCode;    Break } queueerrorarray.push (ErrorFile);} /** * Select File dialog box to trigger, report the number of files selected, number of uploads queued files and total number of upload queue files * @param numselected selected number of files * @param numqueued number of files queued * @param numtotal Inqueued The total number of files in the upload file queue */function filedialogcomplete (numselected, numqueued, numtotalinqueued) {if (Queueerrorarray &amp ;& queueerrorarray.length) {//If there is an error file var table = $ (' <table><tr><td> file &LT;/TD&GT;&LT;TD&G t; size </td></tr></table> ');            for (var i in Queueerrorarray) {var tr = $ (' <tr></tr> '); var info = ' <td> ' + queueerrorarray[i].file.name + ' <span style= "color:red" > (' + queueerrorarray[i].error + ')            </span></td> ' + ' <td> ' + queueerrorarray[i].file.size + ' bytes</td> ';        Table.append (Tr.append (info));    } $ (' body '). Append (table);             } else {this.startupload (); Start uploading}}/** * File upload triggered event * @param file one object */function Uploadstar (file) {if (file) {$ (' #fileList li# ' + fi le.id). Find (' P#statue '). Text ("Upload .....        ");    $ (' #fileList li# ' + file.id). Find (' p#progress '). Width ("0%"); }}/** * File upload process Flash timed call method used to return the current upload progress * @param file Upload object * @param bytecompleted bytes uploaded * @param bytetotal total bytes */function    Uploadprogress (file, bytecompleted, bytetotal) {var percentbyte = Math.Round ((bytecompleted/bytetotal) * 100); Current Progress $ (' #fileList li# ' + file.id). Find (' Span#progressvalue '). Text (percentbyte + "%"); $ (' #fileList li# ' + file.id). Find (' div#progress '). CSS (' width ', percentbyte + '% ');} /** * File upload is complete and the server returns 200 status code trigger * @param file uploaded files * @param serverdata * @param response */function uploadsuccess (file, serv    Erdata, Response) {var $item = $ ("#fileList li#" + file.id);    $item. Find (' div#progress '). CSS (' width ', ' 100% ');    $item. Find (' Span#progressvalue '). CSS (' Color ', ' blue '). Text (' 100% '); $item. Find (' P#statue '). html (' upload complete! '). CSS (' Color ', ' green ');} /** * Triggered at the end of an upload cycle (Uploaderror and uploadsuccess are triggered) * Here you can start the next file upload (by uploading the component's Uploadstart () method) * @param file upload completed by files */    function Uploadcomplete (file) {//determines if there are any files in the queue (This.getstats (). files_queued > 0) {this.startupload ();        } else {this.cancelupload (THIS.FILEPROGRESSID);    $ ("#fileList li"). Remove (); }}/******************************** button Event bindings *********************************************/$ (' #submit '). Click ( function () {Swfup.startuploAD ();}); 

servlet for background processing

Package Com.zxd.tool;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 Javax.servlet.servletconfig;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import java.io.*; Import Java.util.list;import java.util.uuid;/** * Created by Zhang on 14-2-25.   */@WebServlet ("/upload") public class upload extends HttpServlet {private File tempdir;   Temporary path private File savedir; Save Path/** * Servlet Initialization event * * @param config * @throws servletexception */public void init (SERVL        Etconfig config) throws servletexception {String Uploadpath = Config.getservletcontext (). Getrealpath ("/"); StringBuffer sb = new StringBuffer (UploADPath);        Savedir = new File (Sb.append ("\\upload"). toString ());        TempDir = new File (Sb.append ("\\temp"). toString ());        if (!savedir.exists ()) {Savedir.mkdir ();        } if (!tempdir.exists ()) {Tempdir.mkdir ();  }} public void doget (HttpServletRequest request, httpservletresponse response) throws IOException, Servletexception    {This.dopost (request, response);        } public void DoPost (HttpServletRequest request, httpservletresponse response) throws IOException, Servletexception {        Diskfileitemfactory factory = new Diskfileitemfactory ();      Factory.setsizethreshold (1 * 1024 * 1024);             Set buffer size factory.setrepository (TEMPDIR); Set temporary save directory Servletfileupload SFU = new Servletfileupload (factory);  Servelt File Upload Object Sfu.setfilesizemax (200 * 1024 * 1024);        200M sfu.setheaderencoding ("Utf-8");        list<fileitem> list = null; try {list = Sfu.parsereqUest (Request);        Get file} catch (Fileuploadexception e) {e.printstacktrace ();        } int size = List.size ();            for (int i = 0; i < size; i++) {//Loop save Fileitem File = List.get (i);  if (File.isformfield ()) {//If it is a form field String name = File.getfieldname (); Get the field name String value = file.getstring ("Utf-8");                        Get the field value} else {String extname = file.getname (). substring (//Get extension                File.getname (). LastIndexOf ("."));                String fname = Uuid.randomuuid () +extname;  try {file.write (new file (Savedir, fname));                Write file} catch (Exception e) {e.printstacktrace (); }            }        }    }

Upload of swfupload file for Flash upload component

Related Article

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.