Javascript 使用JS中的formdata和fetchAPI将上传到表单中的图像发送到服务器
我试图从单一表单中提取图像和文本数据。 我尝试使用formdata.get('image')获取用户选择的图像, 但它不起作用,因为我在服务器上收到一个未定义的值。 我想知道的适当方式,以获得由一个选择的图像 用户在表单中使用formdata或任何其他方法,谢谢 形式Javascript 使用JS中的formdata和fetchAPI将上传到表单中的图像发送到服务器,javascript,forms,fetch,image-upload,Javascript,Forms,Fetch,Image Upload,我试图从单一表单中提取图像和文本数据。 我尝试使用formdata.get('image')获取用户选择的图像, 但它不起作用,因为我在服务器上收到一个未定义的值。 我想知道的适当方式,以获得由一个选择的图像 用户在表单中使用formdata或任何其他方法,谢谢 形式 <form id = "register" class = "edit-note" enctype = "multipart/form-data">
<form id = "register" class = "edit-note" enctype = "multipart/form-data">
<div>
<label>Heading:</label>
<input type = "text" name = "heading" placeholder = "<%= Note[0].heading %>" id = "heading">
</div>
<div>
<label>Small Text:</label>
<input type = "text" name = "stext" placeholder = "<%= Note[0].smallText %>" id = "stext">
</div>
<div>
<label>Featured Image:</label>
<img src = "<%= Note[0].image %>" height = "110px" width = "132px">
<input type = "file" name = "image" id = "fimage">
</div>
<div>
<label>Background Image:</label>
<img src = "<%= Note[0].background %>" height = "110px" width = "132px">
<input type = "file" name = "bimage" id = "bimage">
</div>
<div>
<label>Content:</label>
<textarea name = "content" placeholder = "<%= Note[0].content %>" id = "content"></textarea>
</div>
<input type = "submit" name = "register" value = "Save Changes">
</form>
我排除了FetchAPI中与问题无关的部分。如果您想使用
XMLHttpRequest
上传文件,那么您必须使用FormData
,您正在这样做,但方式不对
步骤一:创建一个FormData
实例
let formData = new FormData();
第二步:将数据附加到其中
formData.append('file_to_upload', fileField.files[0]); // Here fileField is the input file reference
第三步:通过
XMLHttpRequest
发送formData
,您将在formData
中附加您提供的文件名,在上述情况下,它是-文件到上传
谢谢,这很有效,你知道如何使用FetchAPI吗?虽然我对FetchAPI一无所知,但尝试一下这些url,你肯定会从以下方面得到一些帮助:
formData.append('file_to_upload', fileField.files[0]); // Here fileField is the input file reference