aboutsummaryrefslogtreecommitdiff
path: root/files/zh-tw/web/api/formdata/using_formdata_objects/index.html
blob: e01b15eb90d5a654dbb75b2ef0f103e3cde17030 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
---
title: Using FormData Objects
slug: Web/API/FormData/Using_FormData_Objects
translation_of: Web/API/FormData/Using_FormData_Objects
---
<p class="summary">The <code><a href="/en-US/docs/Web/API/FormData">FormData</a></code> object lets you compile a set of key/value pairs to send using <code><a href="/en-US/docs/Web/API/XMLHttpRequest">XMLHttpRequest</a></code>. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's {{domxref("HTMLFormElement.submit","submit()")}} method would use to send the data if the form's encoding type were set to <code>multipart/form-data</code>.</p>

<h2 id="Creating_a_FormData_object_from_scratch">Creating a FormData object from scratch</h2>

<p>You can build a <code>FormData</code> object yourself, instantiating it then appending fields to it by calling its {{domxref("FormData.append","append()")}} method, like this:</p>

<pre class="brush: js">var formData = new FormData();

formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to a string "123456"

// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

// JavaScript file-like object
var content = '&lt;a id="a"&gt;&lt;b id="b"&gt;hey!&lt;/b&gt;&lt;/a&gt;'; // the body of the new file...
var blob = new Blob([content], { type: "text/xml"});

formData.append("webmasterfile", blob);

var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
</pre>

<div class="note"><strong>Note:</strong> The fields "userfile" and "webmasterfile" both contain a file. The number assigned to the field "accountnum" is immediately converted into a string by the <a href="/en/DOM/XMLHttpRequest/FormData#append()" title="en/XMLHttpRequest/FormData#append()"><code>FormData.append()</code></a> method (the field's value can be a {{ domxref("Blob") }}, {{ domxref("File") }}, or a string: <strong>if the value is neither a Blob nor a File, the value is converted to a string</strong>).</div>

<p>This example builds a <code>FormData</code> instance containing values for fields named "username", "accountnum", "userfile" and "webmasterfile", then uses the <code>XMLHttpRequest</code> method <a href="/en/DOM/XMLHttpRequest#send()" title="en/XMLHttpRequest#send()"><code>send()</code></a> to send the form's data. The field "webmasterfile" is a {{domxref("Blob")}}. A <code>Blob</code> object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The {{ domxref("File") }} interface is based on <code>Blob</code>, inheriting blob functionality and expanding it to support files on the user's system. In order to build a <code>Blob</code> you can invoke the {{domxref("Blob.Blob","Blob() constructor")}}.</p>

<h2 id="Retrieving_a_FormData_object_from_an_HTML_form">Retrieving a FormData object from an HTML form</h2>

<p>To construct a <code>FormData</code> object that contains the data from an existing {{ HTMLElement("form") }}, specify that form element when creating the <code>FormData</code> object:</p>

<pre class="brush: js">var formData = new FormData(someFormElement);
</pre>

<p>For example:</p>

<pre class="brush: js">var formElement = document.querySelector("form");
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
request.send(new FormData(formElement));
</pre>

<p>You can also append additional data to the <code>FormData</code> object between retrieving it from a form and sending it, like this:</p>

<pre class="brush: js">var formElement = document.querySelector("form");
var formData = new FormData(formElement);
var request = new XMLHttpRequest();
request.open("POST", "submitform.php");
formData.append("serialnumber", serialNumber++);
request.send(formData);</pre>

<p>This lets you augment the form's data before sending it along, to include additional information that's not necessarily user-editable.</p>

<h2 id="使用_FormData_物件傳送檔案">使用 FormData 物件傳送檔案</h2>

<p>You can also send files using <code>FormData</code>. Simply include an {{ HTMLElement("input") }} element of type <code>file</code> in your {{htmlelement("form")}}:</p>

<pre class="brush: html">&lt;form enctype="multipart/form-data" method="post" name="fileinfo"&gt;
  &lt;label&gt;Your email address:&lt;/label&gt;
  &lt;input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" /&gt;&lt;br /&gt;
  &lt;label&gt;Custom file label:&lt;/label&gt;
  &lt;input type="text" name="filelabel" size="12" maxlength="32" /&gt;&lt;br /&gt;
  &lt;label&gt;File to stash:&lt;/label&gt;
  &lt;input type="file" name="file" required /&gt;
  &lt;input type="submit" value="Stash the file!" /&gt;
&lt;/form&gt;
&lt;div&gt;&lt;/div&gt;
</pre>

<p>Then you can send it using code like the following:</p>

<pre class="brush: js">var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {

  var oOutput = document.querySelector("div"),
      oData = new FormData(form);

  oData.append("CustomField", "This is some extra data");

  var oReq = new XMLHttpRequest();
  oReq.open("POST", "stash.php", true);
  oReq.onload = function(oEvent) {
    if (oReq.status == 200) {
      oOutput.innerHTML = "Uploaded!";
    } else {
      oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.&lt;br \/&gt;";
    }
  };

  oReq.send(oData);
  ev.preventDefault();
}, false);
</pre>

<div class="note">
<p><strong>Note</strong>: If you pass in a reference to the form the method specified in the form will be used over the method specified in the open() call.</p>
</div>

<p>You can also append a {{ domxref("File") }} or {{ domxref("Blob") }} directly to the {{ domxref("FormData") }} object, like this:</p>

<pre class="brush: js">data.append("myfile", myBlob, "filename.txt");
</pre>

<p>When using the {{domxref("FormData.append","append()")}} method it is possible to use the third optional parameter to pass a filename inside the <code>Content-Disposition</code> header that is sent to the server. When no filename is specified (or the parameter isn't supported), the name "blob" is used.</p>

<p>You can also use <code>FormData</code> with jQuery if you set the right options:</p>

<pre class="brush: js">var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
  url: "stash.php",
  type: "POST",
  data: fd,
  processData: false,  // tell jQuery not to process the data
  contentType: false   // tell jQuery not to set contentType
});
</pre>

<h2 id="Submitting_forms_and_uploading_files_via_AJAX_without_FormData_objects">Submitting forms and uploading files via AJAX <em>without</em> <code>FormData</code> objects</h2>

<p>If you want to know how to serialize and submit a form via <a href="/en-US/docs/AJAX" title="/en-US/docs/AJAX">AJAX</a> <em>without</em> using FormData objects, please read <a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files" title="/en-US/docs/DOM/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files">this paragraph</a>.</p>

<h2 id="參見">參見</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest">Using XMLHttpRequest</a></li>
 <li>{{domxref("HTMLFormElement")}}</li>
 <li>{{domxref("Blob")}}</li>
 <li><a href="/en-US/docs/Web/JavaScript/Typed_arrays">Typed Arrays</a></li>
</ul>