简体   繁体   English

multipart/form-data 可以用javascript发送吗?

[英]multipart/form-data possible to send with javascript?

I am sending a file over POST together with text "name" using this form:我使用这种形式通过 POST 发送一个文件和文本“名称”:

<form enctype="multipart/form-data" action="https://site[DOT]net/upload" method="post">
  <input id="name" type="text" />
  <input id="data" type="file" />
  <button type="submit" name="submit" />
</form>

I would like to do the exect same using javascript.我想使用 javascript 做同样的事情。 In addition I dont want to be redirected.另外我不想被重定向。 I want to stay on the html page and just show a popup "Upload done".我想留在 html 页面上,只显示一个弹出窗口“上传完成”。 How can I do this in javascript (no jquery)?我怎样才能在 javascript(没有 jquery)中做到这一点?

EDIT:编辑:

I tried this code but the POST is not working:我试过这段代码,但 POST 不起作用:

<script>
function uploader {
  var formData = new FormData();
  formData.append("name", "Smith");
  formData.append("data", fileInputElement.files[0]);
  var request = new XMLHttpRequest();

  request.open("POST", "https://site[DOT]net/upload");
  request.send(formData);
}
</script>

<form>
    <input id="name" type="text" />
    <input id="data" type="file" />
    <button type="submit" name="submit" />
    <button onclick="uploader()">Click</button>
</form>

Uploading the entire form with javascript, including the files, can be done by using the FormData API and XMLHttpRequest使用 javascript 上传整个表单,包括文件,可以通过使用FormData APIXMLHttpRequest来完成

var form = document.getElementById('myForm'); // give the form an ID
var xhr  = new XMLHttpRequest();              // create XMLHttpRequest
var data = new FormData(form);                // create formData object


xhr.onload = function() {
    console.log(this.responseText); // whatever the server returns
}

xhr.open("post", form.action);      // open connection
xhr.send(data);                     // send data

If you need to support IE10 and below, it gets increasingly complicated, and would in some cases require posting through iFrames etc.如果您需要支持 IE10 及以下版本,它会变得越来越复杂,并且在某些情况下需要通过 iFrame 等发布。

In case any wants to do this with the new form instead of xhr this is the equivalent.如果有人想用新形式而不是 xhr 来做到这一点,这是等效的。 Also see: fetch post with multipart form data另请参阅: 使用多部分表单数据获取帖子

 var form = document.getElementById('formid'); form.onsubmit = async (e) => { e.preventDefault(); const form = e.currentTarget; const url = form.action; try { const formData = new FormData(form); const response = await fetch(url, { method: 'POST', body: formData }); console.log(response); } catch (error) { console.error(error); } }
 <form id="formid" enctype="multipart/form-data" action="#" method="post"> <input id="name" type="text" /> <input id="data" type="file" /> <button type="submit" name="submit">Submint</button> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM