Today, the company added an interface for uploading pictures, and I suddenly remembered that I haven’t written an article for a while, so I’ll write something casually today.
First, let's take a look at how the official website documentation describes this aspect:
upload picture
uni.uploadFile(OBJECT)
To upload local resources to the developer server, the client initiates a POST
request, where content-type
is multipart/form-data
.
(The official link is attached here, you can take a detailed look at how the official document describes the uniapp file upload official document )
It can be seen uni.uploadfile
that it is a post
request, and the request header needs to be specified content-type
as multipart/form-data
the code is as follows
//图片上传
uni.uploadfile({
url:'接口路径',
filePath:'要上传文件资源的路径。',
name:'multipart 提交时,表单的项目名,默认为 file',
header:{
"Content-Type": "multipart/form-data" //一定要写的
},
formData:{
...data //网络请求中其他额外的data
},
success(res){
console.log(res)
},
fail(err){
console.log(err)
},
complete(){
}
})
//用另一个api来做个对比
uni.request({
url:'',
method:'',
data:{
...data
},
header:{
"Content-Type": "application/json"
},
success(res){
console.log(res)
},
fail(err){
console.log(err)
},
complete(){
}
})
It can be seen that the configuration information of these two APIs is not very different, and only the following points need to be paid attention to:
1. The name needs to be changed
2. Normal interface request parameters are in data
, and image upload parameters are fromData
in
3. Image upload also adds two parameters filePath
andname
4. The request header for image upload needs to be added content-type
asmultipart/form-data
Of course, how to get the file uniapp official also has a corresponding API, as follows:
Get local pictures
uni.chooseImage(OBJECT)
Choose an image from your local photo album or take a photo with your camera.
uni.chooseImage({
count: 6, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function (res) {
console.log(JSON.stringify(res.tempFilePaths));
}
});
(The official link is attached here. You can take a detailed look at how the official document describes it. uniapp obtains the official document of local pictures )
Combining the above two methods can complete the process from obtaining pictures to uploading pictures.
uni.chooseImage({
count: 6, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function (res) {
uni.uploadfile({
url:'接口路径',
filePath:'要上传文件资源的路径。',
name:'multipart 提交时,表单的项目名,默认为 file',
header:{
"Content-Type": "multipart/form-data" //一定要写的
},
formData:{
...data //网络请求中其他额外的data
},
success(res){
console.log(res)
},
fail(err){
console.log(err)
},
complete(){
}
})
}
})
The specific use requires encapsulation, and the request encapsulation will not be shown here. There are many methods, so I will not demonstrate it.