[uniapp]vue3表单上传图片

2024年9月19日 09:50 by wst

小程序

需求

在手机端编辑商品详情,包括商品图片。运行环境为微信小程序。

解决方法

前提:vue3+uniapp+vscode

代码:

<template>
<view class="input-group">上传图片:
  <uni-icons type="cloud-upload" size="30" @click='addPicture'></uni-icons>
  <image class='img' :src='imgPath' mode='aspectFill'></image>
</view>
<view class="pop-btn">
  <button @click="addDishPicture" type="primary" size="mini">
    提交
  </button>
</view>
</template>

<script setup>
import { ref } from 'vue';
const imgPath = ref(null); 

/**选择图片 */
function addPicture(){
  uni.chooseImage({
    count:1,
    sourceType:['album', 'camera'],
    success:(res)=>{
      console.log("picture-res:", res)
      imgPath.value = res.tempFilePaths[0]
      console.log("获取图片成功!")
    },
  })
}

/**上传图片+数据 */
function addDishPicture(){
  var query = {
    ...inputTable.value
  }
  uni.uploadFile({
    url:BASE_URL + '/admin/pro/add_product_details',
    filePath: imgPath.value,
    header:{'content-type': 'multipart/form-data'},
    name:'imgdata',
    formData: query,
    success:(success)=>{
      console.log("success:", success.data)
    },
    fail:(fail)=>{
      console.log("fail:", fail)
    },
  })
}

</script>

<style lang="scss" scoped>
.input-group{
  padding: 10rpx 20rpx;
  word-break: keep-all;
  display: flex;
  align-items: center;
  input{
    background-color:bisque;
    width: 50%;
    margin-right: 10rpx;
  }
}
</style>

说明:

imgPath--存储图片的途径;

addPicture--选择图片;

addDishPicture--上传图片;

inputTable--需要传给后台其他表单数据;

后台Django接收代码如下:

def setUploadFile(upload_data):

    file_extension = os.path.splitext(upload_data.name)[1]  # 获得文件后缀名

    MEDIA_ROOT = os.path.join(STATIC_URL, 'upload/foods')

    filepath = ("%s/%s%s") % (MEDIA_ROOT, incommon.getCurrentStmp(), file_extension)  # 保存文件的绝对路径

    fileUrlPath = ("/%s/%s%s") % (MEDIA_ROOT, incommon.getCurrentStmp(), file_extension)

    content = upload_data.chunks()
    with open(filepath, 'wb') as f:
        for i in content:
            f.write(i)

    return fileUrlPath

class DishManage(APIView):
    def post(self, request, *args, **kwargs):
        fenlei = request.POST.get('pro_class', '')
        mingcheng = request.POST.get('name', '')
        jiage = request.POST.get('price', 0)
        fileurlpath = ""
        if "imgdata" in request.FILES:
            uploaded_file = request.FILES['imgdata']
            fileurlpath = setUploadFile(uploaded_file)

 


Comments(0) Add Your Comment

Not Comment!