嘟啊嘟!搞个VUE的图片上传结合Django

mac2024-05-28  45

vue页面怎样添加图片

首先在vue页面定义值 <div id="goods"> 商品名称:<input type="text" v-model="name"><br> 商品价格:<input type="text" v-model="price"><br> //上传图片的类型是file,定义一个id值 商品图片:<input type="file" id="saveimage"><br> <button @click="addgoods()">添加</button> </div> 其次准备 methods:{ addgoods:function () { //我保存的用户登录状态,取出 var user_id = sessionStorage.getItem('id'); this.user_id = user_id; //定义data值,方便于传送数据 var data = new FormData(); data.append('name',this.name); data.append('price',this.price); data.append('id',this.user_id); //1.input框里获取图片 var img = document.getElementById('saveimage').files[0]; //2.将图片添加到Formdata中 data.append('file',img,img.name); //3.发送axios消息,请求头添加 : Content-Type = multipart/form-data this.axios({ url:'/api/api/addgoods/', method:'post', data:data, headers:{'Content-Type':'multipart/form-data'} }).then((res)=>{ console.log(res) if(res.data.code==200){ this.$router.push({'path':'myindex'}) } }).catch((err)=>{ console.log(err) }) } } 在我们的diango里view.py 里 #配置上传图片路径 # 1、settings 里 # 图片上传目录-----自定义图片的目录不能与系统名重合 UPLOAD_FILE = os.path.join(BASE_DIR,'upload') # 2、主路由urls里 配置 #导两个包 from django.views.static import serve from book import settings #路由书写 # 将upload文件夹,共享浏览器访问 path('upload/<path>',serve,{'document_root':settings.UPLOAD_FILE}) 再者 py文件里 # 添加商品 //在CBV视图里 class Addgoods(APIView): def post(self,request): mes={} id = request.data.get('id') name = request.data.get('name') price = request.data.get('price') //图片需要files获取 image = request.FILES.get('file') if not all([name,price,image]): mes['code']=22600 mes['message']='信息不完整' else: //以防上传图片会覆盖以前的所以我们拼接一个时间戳解决 image_name = datetime.now().strftime('%Y%m%d%H%M%S%f')+image.name f = open(os.path.join(settings.UPLOAD_FILE,image_name),'wb') // image.chunks() 以二进制流写入文件 for i in image.chunks(): f.write(i) f.close() #注意图片上传的路经 goods = Goods(name=name,price=price,image_url='http://127.0.0.1:8000/upload/'+image_name,shop_id=id) goods.save() mes['code']=200 mes['message']='添加成功' return JsonResponse(mes)
最新回复(0)