问题描述
在 Vue 上将所选文件添加到 FormData 以 v-input-file 和 input type='file' 中的错误结束。
错误按摩: 无法构建“FormData”:参数 1 的类型不是“HTMLFormElement”。
<template>
<Layout v-if="$store.state.user">
<v-form
id='myform'
name='myForm'
class='myform'
ref="form"
lazy-validation
enctype="multipart/form-data"
method="POST"
>
<!-- FILE UP-LOAD -->
<template>
<v-file-input
:rules="rules_fileInput"
accept="image/png,image/jpeg,image/bmp"
show-size
counter
label="PNG,JPEG,BMP"
placeholder="Pick an image"
prepend-icon="mdi-camera"
@change="onFilePicked"
/>
</template>
<v-btn dark @click="submitForm">
Save
</v-btn>
</v-form>
</Layout>
</template>
<script>
export default {
data: () => ({
imageUpload: null,}),methods: {
onFilePicked(file) {
this.imageUpload = file;
},async submitForm() {
console.log('this.imageUpload:',this.imageUpload) // showing file
//const headersImg = { headers:{ 'Content-Type':'multipart/form-data'}};
const { data } = await axios.post(
url,new FormData(
`files.${this.imageUpload.name}`,this.imageUpload,this.imageUpload.name
)
);
}
上图清楚一些文件数据。
如果我尝试像这样附加 FormData:
async submitForm() {
const formData = new FormData();
formData.append(
`files.${this.imageUpload.name}`,this.imageUpload.name
);
//console.log('...formData:',...formData);
const urlLocal = 'http://localhost:1337/upload';
const urlLive = 'http://www.events-pr-server.ml/upload';
// client in netlefy,server in heroku with: Allow all Origin - for this demo
try {
const { data } = await axios({
method: 'post',url: urlLive,data: formData,headers: {
'Content-Type': 'multipart/form-data',// 'Access-Control-Allow-Origin': '*',},});
结果为:文件为空
- tatusCode:400,错误:“错误的请求”,消息:“错误的请求”,...}。
- data: {errors: [{id: “Upload.status.empty”,message: “Files are 空”}]}。
enter image description here enter image description here
解决方法
根据您的最后一条评论,我创建了一个代码笔来检查问题。
-
我没有遇到
HTMLFormElement
错误,检查下面的代码笔 https://codepen.io/kurtesy_/pen/MWJBwQX?editors=1111 -
在 Post a formData using axios 旁边使用下面的协议,你需要指定
"Content-Type": "multipart/form-data"
axios({ method: "post",url: "your_url",data: formData,headers: { "Content-Type": "multipart/form-data" },}) .then(function (response) { //handle success console.log(response); }) .catch(function (response) { //handle error console.log(response); });