<template>
<div>
<div>
<form>
<tr>
<td>第一个文件</td>
<td><input type="file" id="file1" /></td>
</tr>
<tr>
<td>第二个文件</td>
<td><input type="file" id="file2" /></td>
</tr>
<tr>
<td></td>
<!-- 上传文件 -->
<td><input type="button" value="点击上传" @click="upload" /></td>
</tr>
</form>
</div>
</div>
</template>
<script>
import { files_post } from "../axios_api/api";
export default {
data() {
return {
};
},
mounted() {},
methods: {
upload() {
let data = new FormData();
// 根据id获取对应input框里面的文件元素
var file1 = document.getElementById("file1").files[0];
var file2 = document.getElementById("file2").files[0];
// 文件名称(要和后台参数名称一致) 文件实体 文件名
data.append("file1", file1, file1.name);
data.append("file2", file2, file2.name);
this.axios({
url: "http://127.0.0.1:8000/XXX/",
method: "post",
data: data,
// 声明上传文件的请求头
headers: { "Content-Type": "multipart/form-data" },
}).then((res) => {
console.log(res);
});
},
},
};
</script>
django后台
class UploadFile(APIView):
def post(self, request):
# 接受参数
myfile = request.FILES.get('file1')
myfile1 = request.FILES.get('file2')
file_list = [myfile1, myfile]
# ps:如果上传的图片是中文名称, QQ图片20200210134035.jpg",需要将 " 替换掉
for myfilename in file_list:
print(myfilename)
# 上传的文件是一个对象
myfilename_str = myfilename.name.replace('"', '')
print(myfilename.name)
# 建立文件流对象 使用路径引入 二进制流写入
f = open(os.path.join(UPLOAD_ROOT, myfilename_str), 'wb')
# print(f)
print(myfilename.chunks())
# 写入两个文件
for chunk in myfilename.chunks():
f.write(chunk)
f.close()
return Response({'filename': myfilename_str})