假设我在页面上有这样的元素:
<input id="image-file" type="file" />这将创建一个按钮,该按钮允许网页用户通过操作系统“文件打开...”选择文件。对话框中。
假设用户单击上述按钮,在对话框中选择一个文件,然后单击"Ok“按钮关闭对话框。
选定的文件名现在存储在以下位置:
document.getElementById("image-file").value现在,假设服务器处理URL为"/upload/image“的多部分帖子。
如何将文件发送到"/upload/image"?
另外,如何侦听文件已完成上载的通知?
发布于 2021-04-07 03:46:33
我已经尝试这样做了一段时间,但这些答案对我来说都不起作用。我就是这么做的。
我有一个选择文件和一个提交按钮
<input type="file" name="file" id="file">
<button onclick="doupload()" name="submit">Upload File</button>然后,在我的javascript代码中,我将以下代码
function doupload() {
let data = document.getElementById("file").files[0];
let entry = document.getElementById("file").files[0];
console.log('doupload',entry,data)
fetch('uploads/' + encodeURIComponent(entry.name), {method:'PUT',body:data});
alert('your file has been uploaded');
location.reload();
};如果你喜欢StackSnippets..。
function doupload() {
let data = document.getElementById("file").files[0];
let entry = document.getElementById("file").files[0];
console.log('doupload',entry,data)
fetch('uploads/' + encodeURIComponent(entry.name), {method:'PUT',body:data});
alert('your file has been uploaded');
location.reload();
};<input type="file" name="file" id="file">
<button onclick="doupload()" name="submit">Upload File</button>
PUT方法与POST方法略有不同。在这种情况下,在chrome的web服务器中,没有实现POST方法。
使用chrome - https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb?hl=en的web服务器进行了测试
注意-当使用web server for chrome时,你需要进入高级选项并勾选选项‘启用文件上传’。如果您不这样做,您将得到一个错误,因为不允许。
https://stackoverflow.com/questions/5587973
复制相似问题