Sorry, your browser cannot access this site
This page requires browser support (enable) JavaScript
Learn more >

Gray-Ice

个人博客兼个人网站

html代码:

1
<input type="file" @change="submit">
vue代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<script>
import dragVerify from "vue-drag-verify";
import myheader from './myheader.vue';

export default {
data () {
return {
}
},
methods:{
submit:function(e){
// 请求后台接口
var file = e.target.files[0];
let form_data = new FormData();
let config = {headers: {'Content-Type': 'multipart/form-data'}};
form_data.append('file', file);
this.axios.post('http://127.0.0.1:8000/upload/', form_data, config).then(res=>{
console.log(res);
})
},
}

</script>

Django代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def post(self, request):
# 接收文件
myfile = request.FILES.get('file', None)
# 建立文件流对象
if myfile:
filename = str(uuid.uuid4()) + myfile.name[myfile.name.rfind('.'):]
sql = 'update user set img="%s" where username="%s"' % (filename, username)
try:
cursor.execute(sql)
coon.commit()
except Exception:
print(sql)
print(sql)
f = open(os.path.join(UPLOAD_ROOT, '', filename), 'wb')
for chunk in myfile.chunks():
f.write(chunk)
f.close()

return Response({'filename': myfile.name})
else:
return {'msg': '图片接收失败'}

关键代码:

1
2
3
4
5
6
myfile = request.FILES.get('file', None)
filename = str(uuid.uuid4()) + myfile.name[myfile.name.rfind('.'):]
f = open(os.path.join(UPLOAD_ROOT, '', filename), 'wb')
for chunk in myfile.chunks():
f.write(chunk)
f.close()

这里的UPLOAD_ROOT是我的settings.py里面的配置,是文件夹路径,如果不想从settings.py导入的话直接输入路径就行,如: “/static/“

评论



愿火焰指引你