Home  >  Article  >  Backend Development  >  How to use PHP and UniApp to upload data files

How to use PHP and UniApp to upload data files

WBOY
WBOYOriginal
2023-07-04 09:07:431620browse

How to use PHP and UniApp to implement data file upload

In modern application development, file upload is a very common function. This article will introduce how to use PHP and UniApp to upload data files, and provide relevant code examples for reference.

1. Back-end implementation (PHP)

  1. Create a PHP script for file upload and name it upload.php.
<?php
// 设置允许跨域
header('Access-Control-Allow-Origin: *');

// 定义文件保存的目录
$uploadDir = './uploads/';

// 判断目录是否存在,若不存在则创建
if (!file_exists($uploadDir)) {
    mkdir($uploadDir, 0777, true);
}

// 获取上传的文件
$file = $_FILES['file'];

// 获取文件名及其后缀
$fileName = $file['name'];
$ext = pathinfo($fileName, PATHINFO_EXTENSION);

// 生成新的文件名
$newFileName = uniqid() . '.' . $ext;

// 移动文件到指定目录
if (move_uploaded_file($file['tmp_name'], $uploadDir . $newFileName)) {
    echo json_encode([
        'code' => 0,
        'message' => '文件上传成功',
        'data' => [
            'fileName' => $fileName,
            'filePath' => $uploadDir . $newFileName
        ]
    ]);
} else {
    echo json_encode([
        'code' => -1,
        'message' => '文件上传失败'
    ]);
}
?>
  1. Create a file upload component in the UniApp project and name it Upload.vue.

    <template>
      <div>
     <input type="file" ref="file" @change="handleFileChange" />
     <button @click="uploadFile">上传文件</button>
     <div v-if="uploadedFile">
       文件名:{{ uploadedFile.fileName }}
       <br />
       文件路径:{{ uploadedFile.filePath }}
     </div>
      </div>
    </template>
    
    <script>
    export default {
      data() {
     return {
       file: null,
       uploadedFile: null
     };
      },
      methods: {
     handleFileChange(event) {
       this.file = event.target.files[0];
     },
     uploadFile() {
       let formData = new FormData();
       formData.append('file', this.file);
    
       uni.request({
         url: 'http://your-domain/upload.php',
         method: 'POST',
         header: {
           'content-type': 'multipart/form-data'
         },
         data: formData,
         success: res => {
           if (res.statusCode === 200) {
             let data = res.data;
             if (data.code === 0) {
               this.uploadedFile = data.data;
             } else {
               uni.showToast({
                 title: data.message,
                 icon: 'none'
               });
             }
           }
         },
         fail: err => {
           uni.showToast({
             title: '文件上传失败',
             icon: 'none'
           });
         }
       });
     }
      }
    };
    </script>
    
    <style scoped>
    button {
      margin-top: 20px;
    }
    </style>

2. Use steps

  1. to place the upload.php file in the specified directory of the server to ensure that the PHP environment is configured correctly.
  2. Introduce the Upload.vue file into the page in the UniApp project that needs to use the file upload function.
  3. Use the de20aabbeae882d4be346795253a2bdfde41ef213893046953d652bee3f24d19 tag on the page to use the file upload function.

The above are simple operation steps and code examples for using PHP and UniApp to upload data files. Developers can make appropriate modifications and extensions according to actual needs. I hope to be helpful!

The above is the detailed content of How to use PHP and UniApp to upload data files. 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