Home >Web Front-end >JS Tutorial >How to insert pictures in vue
How to insert pictures in vue: first create a static folder to save the pictures; then write the click event, the code is [url:'/api/api/add/']; finally get the data on the backend .
The operating environment of this tutorial: Windows 7 system, Vue version 2.9.6. This method is suitable for all brands of computers.
How to insert pictures in vue:
First Start creating a static folder to save pictures
Go to setting Configure
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
#The uppercase letters in front are in dead format, try not to write them wrong
Write in the first-level route
re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT})
Write like this in the templates in vue
<div> 姓名:<input type="text" v-model="name"><br> 图片:<input type="file" id="img"><br> #这个ID是下面用来获取它的属性值的 <button @click='my_add()'>添加</button> </div>
Next we should write the click event (FormData is used here: if you don’t understand, you can check it on its official website: https://developer.mozilla.org/zh-CN/docs/Web/ API/FormData/FormData)
methods:{ my_add:function(){ let form_data = new FormData(); #实例化一个FormData form_data.append('name',this.name); #把数据添加到这个实例中 let img = document.getElementById('img').files[0]; #获取id的属性 form_data.append('img',img); #把图拍片名称添加到这个实例中 this.axios({ url:'/api/api/add/', #连接后台接口 第一个api是跨域的配置,第二个api是我的后台一级路由 method:'post', #用post方法进行提交数据 headers:{'Content-Type':'multipart/form-data'}, #'Content-Type': 'multipart/form-data' :指定传输数据为二进制数据,例如图片、mp3、文件 data:form_data, }).then(res=>{ if(res.data.code==200){ alert(res.data.message) #这是code等于200的时候打印的 } else{ alert(res.data.message) #这是code等于其他值 的时候打印的 } }).catch(err=>{ console.log(err) #把错误警告提交到console }) } }
Getting data on the backend
name = request.data.get('name') #获取页面上输入的名字 img = request.FILES.get('img') #获取页面上添加的图片 img_name = img.name #取出文件的名字 img_path = 'static/upload/' + img_name #给图片名字前面拼接上路径 这就是它的路径 with open(img_path,'wb') as f: #循环写入文件‘wb’ for k in img.chunks(): #避免文件太大,就把它分成块写入 f.write(k)
Related learning recommendations: javascript learning tutorial
The above is the detailed content of How to insert pictures in vue. For more information, please follow other related articles on the PHP Chinese website!