Small program multi-image upload component encapsulation and use

Source: Internet
Author: User

Recently developed a small program upload image function, in order to facilitate subsequent search, hereby record which comes.

In the actual development process, the image upload function is a very common function, so it is packaged into components, to avoid the subsequent duplication of labor, is an indisputable fact.

First, the image upload function can be encapsulated into a common module (common.js), for other functions to call. A single picture upload and multiple image uploads are encapsulated here.

Common.js file

/** * File Upload*/functionUploader (file, callback) {wx.uploadfile ({URL:"Http://10.109.86.1:5300/education/api/education/ImageUploader",//server-side URLFilepath:file,//files that need to be uploadedName: ' Anqindayviews ',//file nameHeader: {"Content-type": "Multipart/form-data"}, Success:function(res) {if(Res &&res.data) {vardata =Json.parse (Res.data); if(Data.issuccess &&callback)        {callback (data.content); } Else{wx.hidetoast (); Wx.showmodal ({title:' Error hints ', Content:' Upload image failed ', Showcancel:false          }); }      }    }  });};/** * recursive way to upload multiple files * imgpaths: List of files to upload * index:imgpaths start uploading the serial number * Successfiles: Uploaded successful file * callBack: File upload callback function*/functionuploadfiles (imgpaths, Index, Successfiles, callBack) {varthat = This; Wx.showloading ({title:' Uploading ' + index + ' Zhang ',  }) Wx.uploadfile ({URL:"Http://10.109.86.1:5300/education/api/education/ImageUploader", Filepath:imgpaths[index], name:' Anqindayviews ', header: {"Content-type": "Multipart/form-data"}, Success:function(res) {//success, file return value saved to successful list      if(Res &&res.data) {vardata =Json.parse (Res.data); if(data.issuccess) {Successfiles.push (data.content); }}}, complete:function(e) {index++;//Next One      if(Index = =imgpaths.length) {wx.hideloading (); //upload complete, make a hintWx.showtoast ({title:' Upload success ' +successfiles.length, Icon:' Success ', Duration:2000        }); if(callBack) {callBack (successfiles); }      } Else {        //recursive call, upload the next onethat.uploadfiles (imgpaths, Index,successfiles, CallBack); }})}module.exports={uploader:uploader, uploadfiles:uploadfiles};
View Code

The server side C # WEBAPI receives the uploaded data, obtains the file data, the code is as follows:

var request = HttpContext.Current.Request;

Httppostedfile file = Request. files["Anqindayviews"];

Here, the image upload function is finished, the following is the introduction of the Applet component encapsulation, which is implemented by component.

First, build the component under your own code, which will automatically generate the corresponding file similar to the regular page, as shown in Figure 2.1.

Figure A new component figure two auto-generated file directory

The following direct code, while looking at the side said.

. wxml file

<!--component/uploader/upload.wxml--> <view class= "PAGE__BD" > <view class= "weui-cells" > &lt              ; View class= "Weui-cell" > <view class= "weui-cell__bd" > <view class= "Weui-uploader" > <view class= "WEUI-UPLOADER__HD" > <view class= "weui-uploader__title" > Baby artwork & Photo upload </              view> <view class= "Weui-uploader__info" >{{files.length}}/{{maxFileCount}}</view> </view> <view class= "WEUI-UPLOADER__BD" > <view class= "weui-uploader__files" I d= "Uploaderfiles" > <block wx: for= "{{files}}" wx:key= "*this" > <view class= "weui-uploader__file" bindlongpress= "_deleteimage" data- Index= "{{index}}" bindtap= "_previewimage" id= "{{item}. Origionurl}} "> <image class=" weui-uploader__img "src=" {{item. Zoomurl}} "mode=" Aspectfill "/> </view> </block> </vi                  ew> <view style= ' Display:{{iscanaddfile? ': ' None '} ' class= ' Weui-uploader__input-box ' >              <view class= "Weui-uploader__input" bindtap= "_chooseimage" ></view> </view> </view> </view> </view> </view> </view> </view>

. json file

{  true,  "Usingcomponents": {}}

. wxss file (Note: The applet comes with a style here)

@import '. /.. /STYLE/WEUI.WXSS ';

. js file

//Component/uploader/upload.jsvarCommon = require (".. /.. /common/upload.js "); Component ({options: {multipleslots:true //enable multi-slot support in options when component definition  },  /** * component's attribute list*/properties: {files: {type:array, Value: []}, Maxfilecount: {//allow up to 9 picturesType:number, Value:9}, Iscanaddfile: {type:boolean, Value:true    }  },  /** * Initial data for the component*/data: {},/** Component life cycle function, which executes after the component layout is complete, can get node information at this time*/Ready :function () { },  /** * Method List of Components*/methods: {/*image Upload*/_chooseimage:function(e) {varthat = This; Wx.chooseimage ({count:that.data.maxFileCount-that.data.files.length, SizeType: [' Original ', ' compressed '],//You can specify whether it is an original or a compressed graph, and the default is bothSourceType: [' album ', ' Camera '],//You can specify whether the source is an album or a camera, and the default is bothSuccessfunction(res) {////Returns a list of local file paths for the selected photo, TempFilePath can display the image as the SRC attribute of the img tag          varWaitfiles =res.tempfilepaths; varAllowcount = That.data.maxfilecount-that.data.files.length;//number of files allowed to upload          if(Waitfiles.length >=Allowcount) {Waitfiles= Waitfiles.slice (0, Allowcount); }          varindex = 0;//start with the first one          varSuccessfiles = [];//a successful fileCommon.uploadfiles (waitfiles, index, Successfiles,function(URLs) {//Here is a common method of extraction, which makes it easy to invoke that.data.files elsewhere=That.data.files.concat (URLs); if(That.data.files.length >=that.data.maxFileCount) {that.data.isCanAddFile=false;            } that.setdata ({files:that.data.files, isCanAddFile:that.data.isCanAddFile          });        }); }      })    },    /*Picture Preview*/_previewimage:function(e) {varPreulrs = [];  This. Data.files.map (function(value, index) {Preulrs.push (value).        Origionurl);      }      ); Wx.previewimage ({current:e.currenttarget.id,//the HTTP link for the currently displayed pictureUrls:preulrs//list of images that need to be previewed HTTP links      })    },    /*Picture Deletion*/_deleteimage:function(e) {varthat = This; varFiles =That.data.files; varindex = E.currenttarget.dataset.index;//get current long press picture subscriptWx.showmodal ({title:Prompted, Content:' Are you sure you want to delete this picture? ‘, Success:function(res) {if(res.confirm) {files.splice (index,1); } Else if(res.cancel) {return false; } that.setdata ({files, iscanaddfile:true          }); }      })    },    /************* for external call interface *******************/GetFiles:function () {      return  This. Data.files; }  }})

The components are packaged and tested for all OK.

Everything is ready, now it's time to use, to verify that the component is OK.

Here's how to use it:

1. Before using a registered custom component, you must first make a reference declaration in the file in the page json . You need to provide a label name for each custom component and a corresponding custom component file path:

{"usingcomponents": {"Upload":"/component/uploader/upload"}}
In this way, the page'swxmlYou can use a custom component just like you would with a base component. Node names are the label names of the custom components, which are the property values passed to the component.
2, page Wxml use:
   <UploadID=' upload 'Files=' {Files}} 'Maxfilecount=' {{maxfilecount}} 'Iscanaddfile=' {{files.length>=maxfilecount?false:true}} ' ></Upload>
<button bindtap= ' showfiles ' > Get file </button>3, page js:page ({data: {files: [],maxfilecount:Ten},onready:function() {//Get the upload component, and then call the component method directly with upload This. Upload = This. Selectcomponent ("#upload") (},}) 4, get the list of uploaded files, define showfiles,show out file list in page JS. Showfiles:function() { This. Data.files = This. Upload.getfiles (); Call the component explicit method to get the file list Console.log ( This. data.files);} :

Click Get file to show a list of existing pictures.

The entire multi-image upload to the server function ends.

n Long did not write the east of me, after writing to feel mess, it seems to be a lot of writing, a lot of summary.

Small program multi-image upload component encapsulation and use

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.