vue里的代码
<template>
<div>
添加商品<input v-model="name"><br>
价格<input v-model="price"><br>
商品照片<input type="file" id="ssss"><br>
<button @click="add">添加</button>
</div>
</template>
<script>
export default {
name: "addcate",
data:function () {
return{
name:'',
price:'',
}
},
methods: {
add:function () {
var data = new FormData();
data.append('name',this.name);
data.append('price',this.price);
var image =document.getElementById('ssss').files[0];
data.append('file',image);
this.axios({
url:'/api/sadmin/addcate/',
data:data,
method:'post'
}).then((res)=>{
if (res.data.code==200){
this.$router.push({'path':'show'})
}
alert(res.data.message)
}).catch((err)=>{
console.log(err)
})
}
}
}
</script>
<style scoped>
</style>
views里的代码
class Addcate(APIView):
def post(self,request):
res={}
name = request.data.get('name')
price = request.data.get('price')
image = request.data.get('file')
if not all([name,price,image]):
res['code']=10020
res['message']='输入不能为空'
else:
image_name = image.name
image_path = os.path.join(settings.UPLOAD_FILE,image_name)
f = open(image_path,'wb')
for i in image.chunks():
f.write(i)
f.close()
goods = Goods.objects.filter(name=name).first()
if goods:
res['code']=10023
res['message']='商品已存在'
else:
goods = Goods(name=name,price=price,image='/upload/'+image_name)
goods.save()
res['code']=200
res['message']='添加成功'
return JsonResponse(res)
return JsonResponse(res)
settings.py 里面配置
STATICFLIES_DIRS=[os.path.join(BASE_DIR,'static')]#照片存放在static文件下
UPLOAD_FILE=os.path.join(BASE_DIR,'upload')#照片存放在根目录upload文件下