In actual projects, there is often a need to upload pictures, so this article mainly introduces how to use the Upload component in uview1 to upload. The specific code is as follows:
1. HTML code
<view class="pic"> <view class="pic_top"> <view class="left"> <text>图片</text> <text class="require">*</text> </view> <view class="right"> 单张图片大小不超过20MB, 最多可上传9张 </view> </view> <view class="pic_bottom"> <u-upload ref="uUpload" :action="action" :auto-upload="true" upload-text=" " :show-progress="false" multiple max-count="9" :header="header" del-bg-color="#fff" del-color="#4f79f5" :max-size="20 * 1024 * 1024" @on-remove="removePic($event, item)" @on-success="successUpload($event)" ></u-upload> </view> </view>
Note: Before using <u-upload>, you must first follow the uview1 version of the package.
2. css code
.pic { .pic_top { margin: 10rpx 0; font-size: 30rpx; display: flex; align-items: center; justify-content: space-between; .left { .require { color: #e64545; } } .right { color: #c4c4c4; font-size: 24rpx; } } .pic_bottom { padding-bottom: 20rpx; } }
3. js code
data() { return { // 上传地址(把你要上传到的服务器地址写在此处即可,以下地址为例子,不可用) action: "https://test.pic.com/snmsbusiness/sysFileInfo/upload", // 请求头(根据请求传参的需求来,如果需要就把对应token加上) header: { Authorization: "Bearer " + uni.getStorageSync("user_token"), }, // 存储图片地址的数组 fileImgList: [], } }, methods: { // 上传图片成功的方法 successUpload(data) { // 获取上传图片的地址,并将地址保存至数组中 this.fileImgList.push(data.data.filePath); console.log(this.fileImgList); }, // 移除图片的方法 removePic(index, item) { console.log("index: ", index); this.fileImgList.splice(index, 1); }, },
Note: Whether the request header is required depends on the actual situation. In addition, here I get the token in the cache and stitch it into the required request header.
As long as the above code is required, local image upload can be realized. I added the attribute : auto-upload="true" in <u-upload> , then the automatic upload is realized . If you want to upload manually , change true to false , and then ref
call the method of the component upload
to realize it Upload images manually (that is, call this.$refs.uUpload.upload() method).
For more detailed information about the upload component, you can refer to the document: Upload | uView - UI framework for multi-platform rapid development - uni-app UI framework