[Picture upload] Encapsulation of global picture upload method~

The final rendering after packaging

  • Two lines of code to get the picture
//上传图片
async chooseimg() {
    
    
	let data = await this.$upimg.Upimgload(1)
	this.form.fullurl = data.fullurl
},

Implementation steps, create a new uploadimg.js

  • uploadurl is the address for uploading pictures on the background interface. This is set as a global variable and cannot be directly referenced by this, so it is better to directly import the address
  • Token, depending on the address of the token storage in different projects, generally you can store it in the cache first, and get the value from the cache
  • n=9, 9 sheets by default, you can limit the number of sheets by passing different parameters
// 方法
import {
    
    
	uploadurl,
} from '@/api/api.js'
export default {
    
    
	Upimgload(n = 9) {
    
    
		return new Promise((resolve, reject) => {
    
    
			uni.chooseImage({
    
    
				count: n, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
				sourceType: ['album'], //从相册选择
				success: function(res) {
    
    
					console.log(uploadurl);
					res.tempFilePaths.forEach(item => {
    
    
						uni.uploadFile({
    
     // 直接上传文件到云储存
							url: uploadurl, //仅为示例,非真实的接口地址
							filePath: item, // 要上传文件的对象
							name: 'file',
							header: {
    
    
								'Token': uni.getStorageSync('token') || ''
							},
							formData: {
    
    },
							success: (uploadFileRes) => {
    
    
								let data = JSON.parse(uploadFileRes.data);
								console.log(data)
								resolve(data.data)
							},
							fail(err) {
    
    
								console.log(err)
							}
						});
					})
				}
			})
		})
	}
}

Global method mount, registered in main.js

  • The name up is random, and it is only responsible for receiving
  • $upimg, this name can be used casually, but it should be consistent with this when used on other pages
//图片上传
import up from "@/api/uploadimg.js"
Vue.prototype.$upimg = up

Guess you like

Origin blog.csdn.net/weixin_44899940/article/details/131128372