1.下载图片
<template>
<view class="container">
<image v-if="imagePath" :src="imagePath" mode="widthFix"></image>
<button @click="downloadImage">下载图片</button>
</view>
</template>
<script>
export default {
data() {
return {
imagePath: '', // 用于存储下载的图片路径
};
},
methods: {
downloadImage() {
uni.downloadFile({
url: 'http://localhost:5000/get', // Flask服务器的URL
header: {
'Authorization': 'Bearer 123456' // 设置请求头以通过服务器的授权检查
},
success: (downloadRes) => {
if (downloadRes.statusCode === 200) {
this.imagePath = downloadRes.tempFilePath; // 设置图片路径为下载的文件路径
uni.showToast({ title: '图片下载成功', icon: 'success' });
} else {
uni.showToast({ title: '下载失败:无效的状态码', icon: 'none' });
}
},
fail: (err) => {
uni.showToast({ title: '下载失败', icon: 'none' });
console.error('Download failed:', err);
}
});
},
},
};
</script>
<style scoped>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
button {
margin-top: 20px;
}
</style>
2.上传图片
<template>
<view class="container">
<button @click="selectAndUploadImage">Upload Image</button>
<text v-if="uploadStatus !== ''">{{ uploadStatus }}</text>
</view>
</template>
<script>
export default {
data() {
return {
uploadStatus: '',
};
},
methods: {
selectAndUploadImage() {
uni.chooseImage({
count: 1, // 默认9,这里设置为1表示只选择一张图片
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: (res) => {
// tempFilePath可以作为img标签的src属性显示图片,也可以用于上传等操作
const tempFilePaths = res.tempFilePaths;
this.uploadFile(tempFilePaths[0]); // 上传第一张图片
},
});
},
uploadFile(filePath) {
const uploadTask = uni.uploadFile({
url: 'http://localhost:5000/request', // Flask服务器的URL
filePath: filePath,
name: 'img', // 必须提供后台用来接收文件的字段名
header: {
// 添加 Authorization 请求头
Authorization: 'Bearer 123456', // 替换为与后端一致的密钥
},
formData: {
// 可以添加其他表单数据
},
success: (uploadFileRes) => {
console.log(uploadFileRes);
const response = JSON.parse(uploadFileRes.data); // 解析返回结果
if (response.msg) {
this.uploadStatus = response.msg; // 显示后端返回的消息
} else {
this.uploadStatus = '上传成功!';
}
},
fail: (err) => {
console.error(err);
this.uploadStatus = 'Upload failed';
},
});
uploadTask.onProgressUpdate((res) => {
console.log('上传进度', res.progress);
console.log('已经上传的数据长度', res.totalBytesSent);
console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend);
});
},
},
};
</script>
<style scoped>
.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
height: 100vh;
}
button {
margin-bottom: 20px;
}
</style>