Summary of uniapp project practice (12) Encapsulation of universal request upload and download methods

Introduction: In the daily development process, the front-end often needs to interface with the back-end to obtain and render data into the page. Next, we will summarize some methods of obtaining requests, file downloads and uploads in uniapp.

Table of contents

  • Principle analysis
  • Method implementation
  • Practical exercises
  • Case display

Principle analysis

Mainly use uni.requestmethods to send requests, uni.downloadFilemethods to download files, and uni.uploadFilemethods to upload files.

scriptsThe following methods are stored in files in folders in the root directory http.js.

Method implementation

Next, we will explain one by one how to implement the method encapsulation of data request, file download and file upload.

data request

try...catchThis method needs to receive some parameters, merge them with the existing default parameters, and then pass them to the request API, and use them to handle success and failure after obtaining the data .

Here we need to introduce some files, including the requested domain name and address, as well as some common methods, which are omitted for now. You can find public interfaces on the Internet, or use node to build a simple interface server yourself.

// 网络请求
async function request(options) {
    
    
  let isHttp = options.url.indexOf("http") > -1;
  let url = isHttp ? options.url : `${
      
      urls.baseUrl}${
      
      options.url}`;
  let defultOptions = {
    
    
    url,
    method: options.method || "get",
    data: options.data || null,
    timeout: options.timeout || 30000,
    dataType: options.dataType || "json",
    header: options.header || {
    
    
      "Content-Type": "application/json",
    },
    sslVerify: options.sslVerify || false,
  };
  let params = {
    
     ...options, ...defultOptions };
  console.log("请求参数:", params);
  try {
    
    
    let result = await uni.request(params);
    if (result.statusCode === 200) {
    
    
      return result.data;
    } else {
    
    
      return {
    
    
        code: 102,
        msg: "get_fail",
        data: {
    
    
          info: result.errMsg,
        },
      };
    }
    return result;
  } catch (e) {
    
    
    return {
    
    
      code: 101,
      msg: "get_fail",
      data: {
    
    
        info: e,
      },
    };
  }
}

Download Document

This is the same as the request, but the API is different. Take a look at the content.

// 下载文件
async function download(options) {
    
    
  let isHttp = options.url.indexOf("http") > -1;
  let url = isHttp ? options.url : `${
      
      urls.baseUrl}${
      
      options.url}`;
  let defultOptions = {
    
    
    url,
    timeout: options.timeout || 30000,
    header: options.header || {
    
    },
    filePath: options.filePath,
  };
  let params = {
    
     ...options, ...defultOptions };
  console.log("下载参数:", params);
  try {
    
    
    let result = await uni.downloadFile(params);
    if (result.statusCode === 200) {
    
    
      return result.tempFilePath;
    } else {
    
    
      return {
    
    
        code: 102,
        msg: "download_fail",
        data: {
    
    
          info: result.errMsg,
        },
      };
    }
    return result;
  } catch (e) {
    
    
    return {
    
    
      code: 101,
      msg: "download_fail",
      data: {
    
    
        info: e,
      },
    };
  }
}

File Upload

File upload is the same as above, simply encapsulate it.

// 上传文件
async function upload(options) {
    
    
  let isHttp = options.url.indexOf("http") > -1;
  let url = isHttp ? options.url : `${
      
      urls.baseUrl}${
      
      options.url}`;
  let defultOptions = {
    
    
    url,
    timeout: options.timeout || 30000,
    filePath: options.filePath || "",
    name: options.name || "file",
  };
  let params = {
    
     ...options, ...defultOptions };
  console.log("上传参数:", params);
  try {
    
    
    let result = await uni.uploadFile(params);
    if (result.statusCode === 200) {
    
    
      return JSON.parse(result.data);
    } else {
    
    
      return {
    
    
        code: 102,
        msg: "upload_fail",
        data: {
    
    
          info: result.errMsg,
        },
      };
    }
    return result;
  } catch (e) {
    
    
    //TODO handle the exception
    return {
    
    
      code: 101,
      msg: "upload_fail",
      data: {
    
    
        info: e,
      },
    };
  }
}

After writing, remember to export the method.

Practical exercises

Template content

  • Request content
<view class="list-http">
  <button @click="sendReq">发起请求</button>
  <text class="list-http-txt">响应内容:{
   
   { httpInfo.request }}</text>
</view>
  • Download content
<!-- 下载图片 -->
<view class="list-http">
  <button @click="downloadImg">下载图片</button>
  <text class="list-http-txt">响应内容:</text>
  <image class="list-http-img" :src="httpInfo.imgUrl" mode="widthFix"></image>
</view>
<!-- 下载文件 -->
<view class="list-http">
  <button @click="downloadFile">下载文件</button>
  <text class="list-http-txt">响应内容:{
   
   { httpInfo.fileUrl }}</text>
</view>
  • Upload content
<!-- 上传图片 -->
<view class="list-http">
  <button @click="uploadImg">上传图片</button>
  <text class="list-http-txt">响应内容:</text>
  <image
    class="list-http-img"
    :src="httpInfo.uploadImgUrl"
    mode="widthFix"
  ></image>
</view>
<!-- 上传文件 -->
<!-- #ifdef H5 || MP-WEIXIN -->
<view class="list-http">
  <uni-file-picker
    ref="files"
    :auto-upload="false"
    limit="1"
    title="最多选择1个文件"
    file-mediatype="all"
    mode="list"
    @select="fileSelect"
    @progress="fileProgress"
    @success="fileSuccess"
    @fail="fileFail"
  ></uni-file-picker>
  <text class="list-http-txt">响应内容:{
   
   { httpInfo.uploadFileUrl }}</text>
</view>
<!-- #endif -->

Screenwriting method

  • Define data
let httpInfo = reactive({
    
    
  request: null,
  imgUrl: "",
  fileUrl: "",
  uploadImgUrl: "",
  uploadFileUrl: "",
});
  • Request method
// 请求内容
async function sendReq() {
    
    
  let opts = {
    
    
    url: proxy.$apis.urls.food,
    method: "get",
  };
  let data = await proxy.$http.request(opts);
  if (data.code == 200) {
    
    
    httpInfo.request = JSON.stringify(data.data.list);
  }
  console.log("请求内容:", data);
}
  • Download pictures
// 下载图片
async function downloadImg() {
    
    
  let opts = {
    
    
    url: proxy.$apis.urls.img,
  };
  let data = await proxy.$http.download(opts);
  if (data) {
    
    
    httpInfo.imgUrl = data;
  }
}
  • download file
// 下载文件
async function downloadFile() {
    
    
  let opts = {
    
    
    url: proxy.$apis.urls.txt,
  };
  let data = await proxy.$http.download(opts);
  console.log(data);
  if (data) {
    
    
    httpInfo.fileUrl = data;
  }
}
  • upload image
// 上传图片
async function uploadImg() {
    
    
  uni.chooseImage({
    
    
    complete(res) {
    
    
      if (res.tempFiles) {
    
    
        let file = res.tempFiles[0];
        uploadSet(file.path);
      }
    },
  });
}
  • upload files
// 上传文件

// 获取上传状态
function fileSelect(e) {
    
    
  console.log("选择文件:", e);
  if (e.tempFiles) {
    
    
    let file = e.tempFiles[0];
    uploadSet(file.path, "file");
  }
}

// 获取上传进度
function fileProgress(e) {
    
    
  console.log("上传进度:", e);
}

// 上传成功
function fileSuccess(e) {
    
    
  console.log("上传成功");
}

// 上传失败
function fileFail(e) {
    
    
  console.log("上传失败:", e);
}
  • Upload operation
// 上传操作
async function uploadSet(filePath, type = "img") {
    
    
  let opts = {
    
    
    url: proxy.$apis.urls.upload,
    filePath,
  };
  let data = await proxy.$http.upload(opts);
  if (data.code == 200) {
    
    
    httpInfo[type == "img" ? "uploadImgUrl" : "uploadFileUrl"] = data.data.url;
    httpInfo.fileName = data.data.filename;
  } else {
    
    
    uni.showToast({
    
    
      title: data.data.info,
      icon: "error",
    });
  }
}

Case display

Request method preview

Insert image description here

File download preview

  • Download pictures
    Insert image description here

  • download file
    Insert image description here

File upload preview

  • upload image
    Insert image description here

  • upload files
    Insert image description here

at last

The above is the main content of encapsulating the universal request upload and download methods. If there are any shortcomings, please correct me.

Guess you like

Origin blog.csdn.net/fed_guanqi/article/details/132746070