<div id="goods">
商品名称:<input type="text" v-model="name"><br>
商品价格:<input type="text" v-model="price"><br>
商品图片:<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;
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)
})
}
}
py文件里
# 添加商品
class Addgoods(APIView):
def post(self,request):
mes={}
id = request.data.get('id')
name = request.data.get('name')
price = request.data.get('price')
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')
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)
#配置上传图片路径
# 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})