Mini-Program Development (2) Image Upload + server receiving details, program development Image Upload
This section describes the commonly used image uploads in small programs.
I uploaded images a few days ago and got stuck. Next, let's take a look at the upload api.
The filePath here is the storage path of the image. The type is actually a String, that is, only one image can be uploaded at a time. My previous interfaces receive an array, and I am a half-hanging PHP, you can only modify the interface for receiving images by yourself.
Take a look at the page
It is common to modify the Avatar effect, select an image (take a photo), and then upload it.
Below is the code.
The first is the wxml code of the applet.
<View class = "xd-container"> <form bindsubmit = "bindSaveTap"> <image class = "xd-img-user1" catchtap = "chooseImageTap" src = "{logo}"> </image> <view class = "xd-view-section"> <text class = "xd-abs xd-flex-left xd-text-nick"> nickname </text> <input name = "nick_name" placeholder = "Enter the nickname" class = "xd-input" value = "{userInfo. user_name }}"/> </view> <view class = "xd-view-section1"> <text class = "xd-abs xd-flex-left xd-text-nick"> Baby gender </text> <radio-group class = "xd-abs xd-radio-group" name = "baby_sex"> <label class = "xd-label-radio" wx: for = "{sex_items}" wx: key = "item"> <radio color = "#3cc975" value = "{item. name }}" wx: if = "{item. name = userInfo. baby_sex }}" checked = "true"/> <radio color = "#3cc975" value = "{item. name }}" wx: else checked = "false"/> <text class = "xd-radio-text" >{{ item. value }}</text> </label> </radio-group> </view> <view Class = "xd-view-section1"> <text class = "xd-abs xd-flex-left xd-text-nick"> baby age </text> <input placeholder = "Enter age "wx: if = "{userInfo. baby_age! = 0} "value =" {userInfo. baby_age }}" class = "xd-input"/> <input name = "baby_age" placeholder = "Enter age" wx: else value = "" class = "xd-input"/> </view> <button size = "default" class = "xd-abs xd-subBtn" formType = "submit" hover-class = "xd-subBtn-hover"> Save </button> </form> </view>
I will not post css code, just some styles.
Corresponding JS Code
Var util = require ('.. /.. /.. /utils/util. js ') var app = getApp () Page ({data: {sex_items: [{name: '1', value: ''}, {name: '2 ', value: 'Little princess '}, {name: '0', value:' '}], logo: null, userInfo: {}}, // bindViewTap: function () {wx. navigateTo ({// url :'.. /logs '// url :'.. /load '})}, onLoad: function () {console. log ('onload') var that = this // call the method of the application instance to obtain the global data app. getUserInfo (function (userInfo ){// Update the data console. log (userInfo); that. setData ({userInfo: userInfo, logo: userInfo. logo})}, bindSaveTap: function (e) {console. log (e) var formData = {uid: util. getUserID (), user_name: e. detail. value. nick_name, baby_sex: e. detail. value. baby_sex, baby_age: e. detail. value. baby_age} console. log (formData) app. apiFunc. upload_file (app. apiUrl. modify_user, this. data. logo, 'photos', formData, function (res) {console. l Og (res) ;}, function () {})}, chooseImageTap: function () {let _ this = this; wx. showActionSheet ({itemList: ['select from album ', 'photographed'], itemColor: "# f7982a", success: function (res) {if (! Res. cancel) {if (res. tapIndex = 0) {_ this. chooseWxImage ('alipay')} else if (res. tapIndex = 1) {_ this. chooseWxImage ('cama') }}}, chooseWxImage: function (type) {let _ this = this; wx. chooseImage ({sizeType: ['original', 'computed'], sourceType: [type], success: function (res) {console. log (res); _ this. setData ({logo: res. tempFilePaths [0],}) }}})
This section describes the JS Code.
1. chooseImageTap Method
It is used to display a pop-up window for selecting images and taking photos. The showActionSheet api for page interaction is used. Click to view details.
Show operation menu
2. chooseWxImage Method
The listener is mainly used to select images and receive image path callbacks. Click to view details.
Select an image from a local album or take a photo with a camera
3. Upload
In the success callback of the chooseWxImage method, we can see that the returned image path is res. tempFilePaths [0] is assigned to the logo. Next we only need to call the upload method and it will be OK. The uploadFile method is encapsulated by me and changed to upload_file.
UploadFile Method
// Upload the file function upload_file (url, filePath, name, formData, success, fail) {console. log ('a = '+ filePath) wx. uploadFile ({url: rootUrl + url, filePath: filePath, name: name, header: {'content-type': 'multipart/form-data '}, // set the request header formData: formData, // other extra form data success: function (res) {console. log (res); if (res. statusCode = 200 &&! Res. data. result_code) {typeof success = "function" & success (res. data);} else {typeof fail = "function" & fail (res) ;}, fail: function (res) {console. log (res); typeof fail = "function" & fail (res );}})}
FilePath is the logo variable passed in upload_file, that is, the absolute path of the image.
Image receiving code of the server
I have read my previous article about the logon process and are familiar with my server. The php framework is Laravel.
Here I will only paste the code for receiving the image;
if(!empty($_FILES['photos'])){ $up_arr['logo'] = upload_logo('photos','manage/images/user','logo',$user_id,0); $up_arr['logo'] = $up_arr['logo'][0]; $user_info['logo'] = $Server_Http_Path . $up_arr['logo']; }
The core method is in upload_log.
Save image receiving
If (! Function_exists ('upload _ logo ') {function upload_logo ($ key_name = 'photos', $ logo_path = 'Manage/images/nurse', $ pre_name = 'logo ', $ salt = '000000', $ encode = 1, $ make = 0) {$ result_arr = array (); global $ Server_Http_Path, $ App_Error_Conf; // save $ date_info = getdate () in folders; $ year = $ date_info ['Year']; $ mon = $ date_info ['mon']; $ day = $ date_info ['mday']; $ logo_path = sprintf ("% s/% s", $ logo_path, $ year, $ mo N, $ day); if (! Is_dir ($ logo_path) {$ res = mkdir ($ logo_path, 0777, true);} // Image Upload // foreach ($ photos as $ key => $ photo) {$ photo = $ _ FILES ['photos']; $ name = $ key_name; $ file_id = Input: file ($ name); if (! Empty ($ file_id) & $ file_id-> isValid () {$ entension = $ file_id-> getClientOriginalExtension (); if ($ pre_name = 'Baby ') {$ new_name = $ pre_name. "_". intval ($ salt ). "_". time (). "_". salt_rand (2, 2);} else {$ new_name = $ pre_name. "_". intval ($ salt ). "_". salt_rand (2, 2);} $ path_id = $ file_id-> move ($ logo_path, $ new_name. "_ B. ". $ entension); if (! Empty ($ path_id) {$ path_name = $ path_id-> getPathName (); $ image_size = getimagesize ($ path_name); $ weight = $ image_size ["0"]; /// obtain the image width $ height = $ image_size ["1"]; /// obtain the image's high if ($ pre_name = "baby" | $ pre_name = "video") {$ photo_info ['url'] = $ path_name; $ photo_info ['width'] = $ weight; $ photo_info ['height'] = $ height; $ result_arr [] = $ photo_info ;} else {$ result_arr [] = $ path_name;} // process the Image if ($ make = 1) {$ img = Image: make ($ path_name) -> resize (200, $ height * 200/$ weight); $ img-> save ($ logo_path. "/". $ new_name. "_ s. ". $ entension); // dd ($ img); // return $ img-> response ('jpg ') ;}} if (empty ($ result_arr )) {$ response ['result _ Code'] =-1006; $ response ['result _ msg '] = $ App_Error_Conf [-1006]; return response ($ response );} if ($ encode = 1) {$ result_arr = json_encode ($ result_arr) ;}return $ result_arr ;}}
The code format is really annoying. I just sorted it out.
In this way, we get started with the Image Upload and interface functions of mini programs.
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.