Uploading and downloading pictures of wechat applet

Keywords: PHP Database SQL

As we all know, small programs have a large number of APIs, file (picture) upload is one of them
Let me share my personal usage. What I have done is to publish and mix images and text like space log

First is the selection of pictures. Using wx.chooseImage, the selected pictures are stored in an array for easy upload

chooseImage: function () {
        var that = this;
        wx.chooseImage({
            success: function (res) {
                console.log(res);
                for (var i = 0; i < res.tempFilePaths.length; i++){
                  var newList = that.data.imagesList.concat(res.tempFilePaths[i]);
                }
                that.setData({
                    imagesList: newList,
                })
            },
        })
    },

Then upload the image, using wx.uploadFile
Take out the pictures in the picture array and upload them,

//Upload pictures
    up_img: function (img,date,index) {
      var _this = this;
      wx.uploadFile({
        url: 'https://Here is the server domain name / diary/setImage.php ', / / interface
        filePath: img,//Picture path
        name: 'file',
        formData: {//Information about storing pictures
          blog_id: date,
          img_index: index,
        },
        success: function (res) {
          if (res.data == '200') {
            wx.showToast({
              title: 'Upload succeeded',
            })
          } else if (res.data == '404') {
            wx.showToast({
              title: 'Upload failed',
            })
          }

        },
        fail: function (error) {
          console.log(error);
        }
      })

Receive and save at the back end

	require 'connect.php';
	
 	date_default_timezone_set("Asia/Shanghai"); //Set time zone
	$code = $_FILES['file'];//Get pictures from applets

	if(is_uploaded_file($_FILES['file']['tmp_name'])) {  
    	//Transfer files to the directory you want 
    	$uploaded_file=$_FILES['file']['tmp_name'];  
    	$username = "image";
    	//Create a folder dynamically  
    	$user_path=$_SERVER['DOCUMENT_ROOT']."/diary/".$username;  
    	//Determine whether this folder already exists  
    	if(!file_exists($user_path)) {  
        	mkdir($user_path);
   		}  
    	$file_true_name=$_FILES['file']['name'];//Get the file name of the picture
    	$name = time().rand(1,1000)."-".date("Y-m-d");//Take the current time stamp + a 4-bit random number and then add the current date as the new file name of the picture
        $type = substr($file_true_name,strrpos($file_true_name,"."));//Type suffix of the captured image (. jpg,.png, etc.)
        //Strrops ($file "true,". ") looks for the last occurrence of". "In the string  
        $image = $name.$type;//Make up a new name
    	$move_to_file=$user_path."/".$name.$type;//

    	if(move_uploaded_file($uploaded_file,iconv("utf-8","gb2312",$move_to_file))) { 
			//When the image is saved successfully, the renamed image name will be stored in the database for the convenience of front-end download
    		$sql="insert into image values('".$_POST['blog_id']."','".$image."','".$_POST['img_index']."')";

            $result=$mysqli->query($sql);
            
            if($result) {
                echo '200';
            }else{
                //Return false if no information exists
                echo '404';
            }

        	echo $_FILES['file']['name']."--Upload succeeded".date("Y-m-d H:i:sa"); 
    	} else {  
        	echo "Upload failed".date("Y-m-d H:i:sa");  
    	}  
	} else {  
    	echo "Upload failed".date("Y-m-d H:i:sa");  
	}

After the back end is saved, the front end uses wx.request for different requests to access the image information

This is the information stored in the database

This is the information in the folder

Remember to do the following when returning to the path

$path = 'https://Here is the server domain name / diary/image / ';
while ($row = $result->fetch_assoc()){
			$row['img_url'] = $path.$row['img_url'];
			$results[]=$row;
		}

Only the complete path can access the picture. If there are some problems in some places, I hope you can give me some advice

Posted by udendra on Thu, 19 Dec 2019 11:03:21 -0800