Home >Web Front-end >uni-app >How to solve the problem that php cannot accept multiple image uploads in uniapp

How to solve the problem that php cannot accept multiple image uploads in uniapp

PHPz
PHPzOriginal
2023-04-18 18:21:251048browse

1. Background introduction

With the continuous development of Internet technology, more and more Web applications need to support the image upload function. Uniapp is a very popular mobile development framework, which is cross-platform, efficient, and easy to use. However, when we use uniapp to develop the multi-image upload function, we will encounter some problems: the server cannot correctly receive the request and cannot obtain the passed image information. This article will explore possible causes and solutions to this problem.

2. Problem description

We use the upload component plug-in provided by uniappuni-upload to develop the multi-image upload function and use PHP back-end code to receive upload requests and save image information. The upload page code is as follows:

<template>
  <view class="container">
    <view class="uploadBtn" @tap="chooseImage">
      <image src="../../static/plus.png"></image>
    </view>
    <view class="image-list">
      <view class="image-item" v-for="(item, index) in fileList" :key="index">
        <image :src="item.path"></image>
        <view class="delete" @tap="deleteImage(index)">删除</view>
      </view>
    </view>
    <view class="submitBtn" @tap="submit">
      提交
    </view>
  </view>
</template>

<script>
  import uniUpload from "@/components/uni-upload/uni-upload.vue";
  export default {
    components: { uniUpload },
    data() {
      return {
        fileList: [],
      };
    },
    methods: {
      chooseImage() {
        uni.chooseImage({
          count: 9,
          success: (res) => {
            this.fileList = [...this.fileList, ...res.tempFilePaths.map((path) => ({ path }))];
          },
        });
      },
      deleteImage(index) {
        this.fileList.splice(index, 1);
      },
      submit() {
        const formData = new FormData();
        this.fileList.forEach((item, index) => {
          formData.append(`file${index}`, item.path);
        });

        uni.request({
          method: "POST",
          url: "http://localhost/upload.php",
          header: {
            "Content-Type": "multipart/form-data",
          },
          data: formData,
          success: (res) => {
            console.log("upload success", res.data);
          },
          fail: (error) => {
            console.log("upload fail", error);
          },
        });
      },
    },
  };
</script>

The upload component uses the uni-upload plug-in, which calls the album to select pictures through the chooseImage method, and adds tempFilePaths to Fill in the image path in fileList, and upload the image path in fileList to the backend server in the submit method.

On the server side, we use PHP as the back-end language, the code is as follows:

<?php
  $upload_dir = "uploads/";
  if (!file_exists($upload_dir)) {
    mkdir($upload_dir);
  }
  foreach ($_FILES as $key => $file) {
    $tmp_name = $file["tmp_name"];
    $name = $file["name"];
    if (move_uploaded_file($tmp_name, $upload_dir . $name)) {
      echo "upload success ";
    } else {
      echo "upload fail ";
    }
  }
?>

It was found in the local test that after submitting the image, the back-end server could not correctly read the upload request and could not Save pictures correctly. Some solutions will be proposed below.

3. Cause of the problem

According to the error message, it may be caused by incorrect file upload method. FormData and multipart/form-data are now an important way to implement file upload through forms. However, if the appropriate request header information is not set, the server cannot correctly obtain the uploaded file, which may be the cause of this problem.

4. Solution

  1. Change the request header information

Add the header content type and boundary in the upload request, where type is when sending the request The boundary part of the Content-Type is a random string that splits the data.

uni.request({
method: "POST",
url: "http://localhost/upload.php",
header: {

"Content-Type": "multipart/form-data; boundary=" + Math.random().toString().substr(2),

},
data: formData,
success: (res) => {

console.log("upload success", res.data);

},
fail: (error) => {

console.log("upload fail", error);

} ,
});

  1. Change the key name of the uploaded file

On the client, we assemble the file list into formData through form data append. At this time, the key of each file defaults to its position in formData, which is an increasing number starting from 0. The key received by the server may be the name value specified in the upload component. Therefore, when uploading files, you can specify a key name for each file, as follows:

this.fileList. forEach((item, index) => {
formData.append("file" index, item.path);
});

Because of the file here It is different from the name attribute value of the uploaded component, so it should also be modified accordingly during back-end processing.

foreach($_FILES as $file) {
$tmp_name = $file["tmp_name"];
$name = $file["name"];
if (move_uploaded_file( $tmp_name, $upload_dir . $name)) {

echo "upload success ";

} else {

echo "upload fail ";

}
}

  1. Higher versions of PHP need to add parameters and modify php .ini

For higher versions of PHP, you need to add the following parameters to the php.ini file:

post_max_size=20M
upload_max_filesize=20M
max_execution_time=600
max_input_time=600

After the setting is completed, Apache needs to be restarted to take effect.

4. Summary

This article discusses the problem that the image information transmitted when uploading multiple images in uniapp cannot be received by PHP. By modifying the request header information, changing the key name of the uploaded file and configuring PHP .ini file, etc., successfully solved the problem. Finally, it is recommended that web developers pay attention to effective testing of the upload function when using uniapp for mobile application development to reduce unnecessary errors and losses.

The above is the detailed content of How to solve the problem that php cannot accept multiple image uploads in uniapp. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn