Uniapp File Upload Guide

To upload files to a server in uniapp, you can use the uni.uploadFile() method. This method will upload the file to a specified URL and return a Promise object, which can be used to handle the successful or failed upload results in the then() or catch() methods, respectively.

Here is an example code demonstrating how to upload files to a server in uniapp.

uni.chooseImage({
  count: 1,  // 选择文件的数量
  success: function (res) {
    // 获取选择的文件路径
    var filePath = res.tempFilePaths[0];
    
    // 上传文件到服务器
    uni.uploadFile({
      url: 'https://example.com/upload',  // 服务器上传接口地址
      filePath: filePath,  // 要上传的文件路径
      name: 'file',  // 服务器接收的文件字段名
      success: function (uploadRes) {
        // 上传成功,打印服务器返回的数据
        console.log(uploadRes.data);
      },
      fail: function (err) {
        // 上传失败,打印错误信息
        console.log(err.errMsg);
      }
    });
  }
});

In the example above, the first step is to use the uni.chooseImage() method to select the file to be uploaded. Then, the selected file path filePath is used as a parameter to upload the file to the server using the uni.uploadFile() method. The url parameter specifies the server’s upload interface address, the filePath parameter specifies the file path to be uploaded, and the name parameter specifies the server’s receiving file field name.

After the upload is successful, you can handle the successful result in the success callback function, such as printing the data returned by the server. If the upload fails, you can handle the failure result in the fail callback function, such as printing the error message.

Please note that server-side configurations may be necessary when uploading files to handle the logic of receiving and saving files. Please configure accordingly based on your specific server environment and requirements.

bannerAds