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 里
UPLOAD_FILE
= os
.path
.join
(BASE_DIR
,'upload')
from django
.views
.static
import serve
from book
import settings
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
)