英文:
How to send by form an image in http request, and with what headers?
问题
我在谷歌上搜索了一下,没有找到答案...
在我的VueJS视图中有一个表单:
<form @submit.prevent="avatar()" method="POST" enctype="multipart/form-data">
<input type="file" name="profilePicture" id="profilepicture">
<button type="submit">Valider mon avatar?</button>
</form>
用户会发送一张图片。
我的问题是,我想要将用户提交的图像发送到一个函数中,然后这个函数将图像添加到 HTTP 请求的头部...
API 请求以如下方式开始:
app.post('/myupload/:iduser', async (req, res) => {
try {
var { iduser } = req.params;
const { image } = req.file;
[...]
我VueJS 视图中的函数如下:
async function avatar() {
console.log(document.getElementById("profilepicture").value);
// 获取要发送的图像的src
let response = await fetch(`http://localhost:196/myupload/${MyTokenStore.myid}`, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: JSON.stringify(document.getElementById("profilepicture").value)
})
.then((response) => response.json())
.catch((error) => {
console.log("Failed", error)
});
if (response.error) {
alert(response.message);
return
}
}
但我在请求中只传递了图像的 src 字符串,错误服务器显示如下:
TypeError: Cannot destructure property 'image' of 'req.files' as it is undefined.
请帮帮我,当我直接访问请求的 URL 时,请求可以正常运行(但浏览器直接显示服务器响应):
<form :action="`http://localhost:196/myupload/${MyTokenStore.myid}`"
method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<button type="submit">Valider mon avatar</button>
</form>
但我无法将其放入一个函数中...
谢谢。
英文:
I searched on google and nothing...
i have a form in my view on vueJS :
<form @submit.prevent="avatar()" method="POST" enctype="multipart/form-data">
<input type="file" name="profilePicture" id="profilepicture" >
<button type="submit">Valider mon avatar?</button>
</form>
The user send an image.
My question is,
i want to send the image (sending by user with the form) in a function, and this function send the image to Http Request in headers ...
the api request begin with :
app.post('/myupload/:iduser', async (req, res) => {
try{
var { iduser } = req.params ;
const { image } = req.file ;
[...]
my function in my view on vuejs is actually :
async function avatar() {
console.log(document.getElementById("profilepicture").value);
// for having the image sending src
let response = await fetch(`http://localhost:196/myupload/${MyTokenStore.myid}`, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
body: JSON.stringify(document.getElementById("profilepicture").value)
})
.then((response) => response.json())
.catch((error) => {
console.log("Failed", error)
});
if(response.error){
alert(response.message);
return
}
}
But the only parameter i make in request is the string of the src image, and the error servor is :
TypeError: Cannot destructure property 'image' of 'req.files' as it is undefined.
Please, i need help, the request run when I go directly to the url of the request (but the browser directly displays the server response):
<form :action="`http://localhost:196/myupload/${MyTokenStore.myid}`"
method="POST" enctype="multipart/form-data">
<input type="file" name="image"/>
<button type="submit">Valider mon avatar</button>
</form>
but I fail to put it in a function...
thank you.
答案1
得分: 1
为了从Vue发送图像请求,您必须使用FormData
对象。例如:
/**
* @description - 注册用户
*/
const register = async () => {
try {
const fd = new FormData();
Object.keys(user.value).forEach((key) => {
fd.append(key, user.value[key]);
});
const res = await axios.post('/register', fd, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
toast.success(res.data);
} catch (err) {
console.log(err);
toast.error(err.response.data);
}
};
在上面的代码中,在register
函数中,我使用FormData
来将user
对象发送到后端。在以前,你应该进行设置。我将它制作成了以下示例:
const setProfileImage = (e) => {
image_preview.value = URL.createObjectURL(e.target.files[0]);
document.getElementById('image_preview').style.height = '150px';
document.getElementById('image_preview').style width = '150px';
user.value.profile_image = e.target.files[0]; // 这对你很重要。
user.value.image = e.target.files[0].name;
};
setProfileImage
接收来自Input file
的event
。如果你看到代码中的注释,user.value.profile_image = e.target.files[0]
是整个文件。其余部分是用于显示图像并将名称发送到数据库。
<div class="mb-3">
<label
for="profile_image"
class="bg-primary text-white rounded-3 text-center w-100 p-2 profile_image"
>
选择您的个人资料照片 <i class="ps-1 bi bi-card-image"></i>
</label>
<input
type="file"
class="form-control d-none"
id="profile_image"
placeholder="附加个人资料照片"
@change="setProfileImage"
/>
</div>
这是我所说的Input file
。事件是@change
,用于正确捕获文件。
希望对您有所帮助。
英文:
To send an image from Vue doing a request you have to use a FormData
object. For example:
/**
* @description - register user
*/
const register = async () => {
try {
const fd = new FormData();
Object.keys(user.value).forEach((key) => {
fd.append(key, user.value[key]);
});
const res = await axios.post('/register', fd, {
headers: {
'Content-Type': 'multipart/form-data',
},
});
toast.success(res.data);
} catch (err) {
console.log(err);
toast.error(err.response.data);
}
};
In the previous code, in register
I'm using a FormData
to send the user
object to the backend. Previously, you should set it. I made it like the following example:
const setProfileImage = (e) => {
image_preview.value = URL.createObjectURL(e.target.files[0]);
document.getElementById('image_preview').style.height = '150px';
document.getElementById('image_preview').style.width = '150px';
user.value.profile_image = e.target.files[0]; // this is important for you.
user.value.image = e.target.files[0].name;
};
setProfileImage
is receiving an event
from an Input file
. If you see the comment I write in the code, user.value.profile_image = e.target.files[0]
is the entire file. The rest is to display the image and send the name to store into the database.
<div class="mb-3">
<label
for="profile_image"
class="bg-primary text-white rounded-3 text-center w-100 p-2 profile_image"
>
Seleccione su foto de perfil <i class="ps-1 bi bi-card-image"></i>
</label>
<input
type="file"
class="form-control d-none"
id="profile_image"
placeholder="Adjunte su foto de perfil"
@change="setProfileImage"
/>
</div>
This is the Input file
what I was talking. The event is an @change
to catch correctly the file.
Hope it works for you.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论