Django-----vue結合上傳圖片


<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})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM