The encounter between Thinkjs and fine uploader

Source: Internet
Author: User

Recently in an internal system, need a non-refreshing upload function, looked for a long time, found a good upload tool-fine Uploader, online also has a lot about its introduction, I have a lot of inspiration, combined with my use of the scene simple introduction of it and Thinkjs perfect match.     The first is to use the THINKJS to quickly build a Web application, you can refer to a previous written thinkjs preliminary.     Visit 127.0.0.1:8360 to see if the app starts properly, and if everything works, start creating pages with front-end pages and server-side processing of uploaded logic. Modify the/app/lib/controller/home/indexcontroller.js content as:
/** * Controller * @return */module.exports = Controller ("Home/basecontroller", function () {"Use strict"; return { Indexaction:function () {this.display ();},uploadfileaction:function () {var self = This;var FileInfo = this.file (' Qqfile ');//http://www.thinkjs.org/doc/http.html# uploaded file/*//fileinfo value {fieldName: ' Qqfile ', originalfilename: ' 1.jpg ', path : '/home/maoshuai/htdocs/mtyras/app/runtime/temp/23886-1c2xozp.jpg ', headers:{' content-disposition ': ' Form-data; Name= "Qqfile"; Filename= "1.jpg" ', ' content-type ': ' Image/jpeg '},ws:{_writablestate:{highwatermark:16384,objectmode:false, needdrain:false,ending:true,ended:true,finished:true,decodestrings:true,defaultencoding: ' UTF8 ', length:0, Writing:false,sync:false,bufferprocessing:false,onwrite: [Function],writecb:null,writelen:0,buffer: [], Erroremitted:false},writable:true,domain:null,_events: {error: [Object], close: [Object]},_maxlisteners:10,path: '/ Home/maoshuai/htdocs/mtyras/app/runtime/temp/23886-1c2xozp.jpg ', fd:null,flags: ' W ', Mode:438,start:undefined,pos:undefined,byteswritten:28618,closed:true},size:28618}*/if (fileInfo) { Self.json ({error:0,errmsg: ' OK ', success:true//Only success return true for upload success});} else {self.error ();}}};});
    Modify/app/view/home/index_index.html content to: 
<! DOCTYPE html>The following is a detailed description of the server-side code and the Front-end page:Service-side indexcontroller.jsIndexaction the corresponding page is index_ Index.html,uploadfileaction corresponding to the front-end page of the upload image interface, where the comments are obtained through the Thinkjs file information, examples are directly returned, the use of the time can be based on their own situation, the data uploaded to the conditions to judge, and then make the corresponding processing.It is important to note that the information returned by Fine uploader must contain the Success field, and only when the success=true is considered a successful upload will change the front page display. The this.success () function of THINKJS cannot pass success parameters, so it is implemented using This.json (). Front index_index.htmlPage did not want to say, mainly introduce the use of fine uploader. It is mainly two main forms, one is the native JS implementation, one is the jquery plug-in form, the two ways of use are as follows:
$ (DOM). Fineuploader (conf); new QQ. Fineuploader (conf);

  

Next say conf can configure what information, view source can find this default configuration:
     This._options = {debug:false, button:null, Multiple:true, Maxconnecti Ons:3, Disablecancelforformuploads:false, autoupload:true, request: {E                 Ndpoint: "/server/upload", params: {}, Paramsinbody:true, Customheaders: {},                Forcemultipart:true, InputName: "Qqfile", Uuidname: "Qquuid",                Totalfilesizename: "Qqtotalfilesize", Filenameparam: "Qqfilename"}, Validation: { Allowedextensions: [], sizelimit:0, minsizelimit:0, Itemlimi                    t:0, Stoponfirstinvalidfile:true, acceptfiles:null, Image: {                maxheight:0, maxwidth:0, minheight:0, minwidth:0 }            },            Callbacks: {onsubmit:function (ID, name) {}, onsubmitted:function (ID, name) {} , Oncomplete:function (ID, name, Responsejson, MAYBEXHR) {}, Onallcomplete:function (success                Ful, failed) {}, oncancel:function (ID, name) {}, onupload:function (ID, name) {}, Onuploadchunk:function (ID, name, chunkdata) {}, Onuploadchunksuccess:function (ID, Chunkdata, respon Sejson, XHR) {}, Onresume:function (ID, fileName, chunkdata) {}, onprogress:function (ID, NA Me, Loaded, total) {}, Ontotalprogress:function (loaded, total) {}, onerror:function (ID, NA Me, Reason, maybexhrorxdr) {}, onautoretry:function (ID, name, attemptnumber) {}, Onmanualre Try:function (ID, name) {}, Onvalidatebatch:function (Fileorblobdata) {}, Onvalidate:functi  On (Fileorblobdata) {},              Onsubmitdelete:function (ID) {}, Ondelete:function (ID) {}, Ondeletecomplete: function (ID, XHRORXDR, isError) {}, Onpastereceived:function (BLOB) {}, Onstatuschange:func            tion (ID, oldstatus, newstatus) {}, Onsessionrequestcomplete:function (response, Success, XHRORXDR) {} }, messages: {typeError: "{file} has an invalid extension.                Valid extension (s): {extensions}. ", Sizeerror:" {file} is too large, and maximum file size is {sizeLimit}. ",  Minsizeerror: "{file} is too small, minimum file size is {minsizelimit}.", Emptyerror: "{file} is empty, please select files again without it. ", Nofileserror:" No files to upload. ", TooM  Anyitemserror: "Too many items ({Netitems}) would be uploaded. Item limit is {itemlimit}. ', Maxheightimageerror: ' Image is too tall. ', MaxwidthimAgeerror: "Image is too wide.", Minheightimageerror: "Image was not tall enough.", Minwidthim Ageerror: "Image is not wide enough.", Retryfailtoomanyitems: "Retry failed-you has reached your file Li                MIT. ", Onleave:" The files are being uploaded, if you leave now the upload would be canceled. ", Unsupportedbrowserios8safari: "Unrecoverable Error-this browser does not permit file uploading of any kind due to Ser  IOUs bugs in IOS8 Safari. Please use iOS8 Chrome until Apple fixes these issues. "}, Retry: {Enableauto:false , Maxautoattempts:3, Autoattemptdelay:5, Preventretryresponseproperty: "Pre Ventretry "}, classes: {buttonhover:" Qq-upload-button-hover ", button Focus: "Qq-upload-button-focus"}, chunking: {enabled:false, concUrrent: {enabled:false}, Mandatory:false, Paramnames: {partindex: "Qqpartindex", Partbyteoffset: "Qqpartbyteoffset", C Hunksize: "Qqchunksize", Totalfilesize: "Qqtotalfilesize", Totalparts: "Qqtotalparts "}, partsize:2000000,//only relevant for traditional endpoints, only requ            ired when concurrent.enabled = = = True success: {Endpoint:null} }, Resume: {enabled:false, Recordsexpirein:7,//days Paramn Ames: {resuming: "Qqresume"}}, Formatfilename:function (Fileorb                    Lobname) {if (fileorblobname!== undefined && fileorblobname.length > 33) { Fileorblobname = FileorbLobname.slice (0, +) + "..." + fileorblobname.slice (-14);            } return fileorblobname; }, Text: {defaultresponseerror: "Upload failure reason Unknown", Sizesymbols: [" KB "," MB "," GB "," TB "," PB "," EB "]}, DeleteFile: {enabled:false, ME            Thod: "DELETE", endpoint: "/server/upload", Customheaders: {}, params: {} }, Cors: {expected:false, Sendcredentials:false, allowx                Dr:false}, BLOBs: {defaultname: "Misc_data"}, paste: {                Targetelement:null, DefaultName: "Pasted_image"}, Camera: { Ios:false,//If iOS is True:button is null means target the default button, otherwise target the butt          On specified      Button:null},//This refers to additional upload buttons to being handled by Fine Uploader.  Each element is a object, containing ' element ' as the only required//property. The ' element ' must is a container that would ultimately//contain an invisible ' <input type= ' file ' > ' Crea            Ted by Fine Uploader.            Optional properties of each object include ' multiple ', ' validation ',//and ' folders '.  Extrabuttons: [],//Depends on the session module.            Used to query the server for a initial file list//during initialization and optionally after a ' reset '.                Session: {endpoint:null, params: {}, Customheaders: {},             Refreshonreset:true},//Send parameters associated with a existing form along with the files      Form: {//Element ID, htmlelement, or null          element: "Qq-form",//Overrides the base ' autoupload ', unless ' element ' is null. Autoupload:false,//true = Upload files on form submission (and squelch submit event) int            Erceptsubmit:true},//Scale images client side, upload a new file for each scaled version Scaling: {//Send the original file as well sendoriginal:true,//Fox O Rientation for scaled images orient:true,//If null, scaled image type would match Referenc  e image type.                This value would be referred to//for any size record, that does not specific a type. Defaulttype:null, defaultquality:80, FailureText: "Failed to scale", includ            Eexif:false,//metadata about each requested scaled version sizes: []}, Workarounds: {iosemptyvideos:true, ios8safariuploads:true, ios8browsercrash:true }        };
We can see that there are a lot of configurations, most of which I did not study carefully, just looked at some of the commonly used configurations, and also made notes in index_index.html. We are more concerned about: multiple, autoupload, validation, callbacks, messages, template, basically these can meet our needs. Here's a look at the effects of these parameters:
    • Multiple support for multiple file uploads
    • Autoupload whether to automatically upload, that is, after the file is selected, whether you also need to manually click the Upload button to trigger the start upload event
    • Validation file constraints, including file format, maximum file size, minimum file value
    • Callbacks various callback functions, including start commit, start uploading, uploading, uploading successful, canceling upload
    • Messages Some default prompts, you can adjust the error of the source file, the example is just I adjust the nofileserror, the business can be configured according to their own needs
    • Template can use a script template or a DOM template, as long as the ID string or DOM object of the template
    • Debug this needless to say, in order to develop debugging use, will record the detailed upload process, easy to find the location of the problem appears
In addition to the configuration, in the description of Uploadstoredfiles this method is to facilitate the manual upload binding when used. At this point, a simple no-refresh upload is complete. Here to Thinkjs and fine uploader explanation are some fur, simple explain how to make the two very good tie up, if want to learn more thinkjs and fine uploader or suggest go directly to the official website study.THINKJS official website:http://thinkjs.org/Fine Uploader Official website: http://fineuploader.com/Resources:http://thinkjs.org/Http://fineuploader.com/http://www.cnblogs.com/chenkai/archive/2013/01/04/2844702.html

The encounter between Thinkjs and fine uploader

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.