It is necessary to send data to the server in the required format, I don’t understand how to organize it correctly, the same JSON structure. You must send when attaching a file (@change
), the file itself and a comment. Here is what I was able to do https://codepen.io/JessikaJes/pen/rNvgYwP
JavaScript
x
70
70
1
<div id="app" class="container">
2
<div class="block">
3
<div class="item" v-for="(item, index) in items" :key="index">
4
<div class="item__title">{{ item.title }}</div>
5
<div class="item__files">
6
<div class="file" v-for="(file, index) in item.files">
7
<input type="file" @change="handleFileUpload()">
8
<input type="text" placeholder="comment" v-model="file.comment">
9
</div>
10
</div>
11
</div>
12
</div>
13
</div>
14
<script>
15
new Vue({
16
el: "#app",
17
data: {
18
items: [
19
{
20
id: "42",
21
title: "first",
22
files: [
23
{
24
file: "",
25
comment: "",
26
},
27
{
28
file: "",
29
comment: "",
30
}
31
],
32
},
33
{
34
id: "78",
35
title: "second",
36
files: [
37
{
38
file: "",
39
comment: "",
40
},
41
{
42
file: "",
43
comment: "",
44
}
45
],
46
},
47
]
48
},
49
methods: {
50
handleFileUpload() {
51
let formData = new FormData();
52
// formData.append("file", this.file);
53
// formData.append("comment", this.file);
54
axios
55
.post(`/api/request/${id}`, formData, {
56
headers: {
57
"Content-Type": "multipart/form-data",
58
},
59
})
60
.then(function () {
61
console.log("SUCCESS!!");
62
})
63
.catch(function () {
64
console.log("FAILURE!!");
65
});
66
}
67
}
68
});
69
</script>
70
Advertisement
Answer
Change the code like this:
JavaScript
1
73
73
1
<template>
2
<div id="app" class="container">
3
<div class="block">
4
<div class="item" v-for="(item, index) in items" :key="index">
5
<div class="item__title">{{ item.title }}</div>
6
<div class="item__files">
7
<div class="file" v-for="(fileObj, index2) in item.files">
8
<input type="file" v-model="fileObj.file" @change="handleFileUpload($event,fileObj)">
9
<input type="text" placeholder="comment" v-model="fileObj.comment">
10
</div>
11
</div>
12
</div>
13
</div>
14
</div>
15
16
<script>
17
new Vue({
18
el: "#app",
19
data: {
20
items: [
21
{
22
id: "42",
23
title: "first",
24
files: [
25
{
26
file: "",
27
comment: "",
28
},
29
{
30
file: "",
31
comment: "",
32
}
33
],
34
},
35
{
36
id: "78",
37
title: "second",
38
files: [
39
{
40
file: "",
41
comment: "",
42
},
43
{
44
file: "",
45
comment: "",
46
}
47
],
48
},
49
]
50
},
51
methods:
52
{
53
handleFileUpload(event, fileObject)
54
{
55
let formData = new FormData();
56
const file = (event.dataTransfer || event.target).files[0];
57
formData.append("file", file);
58
formData.append("comment", fileObject.comment);
59
axios
60
.post(`/api/request/${id}`, formData)
61
.then((response) =>
62
{
63
console.log("SUCCESS!!");
64
})
65
.catch((error) =>
66
{
67
console.log("FAILURE!!");
68
});
69
}
70
}
71
});
72
</script>
73