The FormData object is used to compile data into key-value pairs that can be sent using XMLHttpRequest. It is mainly used to send form data, but can also be used to send keyed data independently of the form. If the form encType attribute is set to multipart/form-data, the form’s submit() method is used to send the data, so that the sent data has the same form.
I’ve been submitting the form using ajaxSubmit, the jquery form plugin.
$('#myForm2').submit(function() {
$(this).ajaxSubmit(function() {$('#output2').html("Submission successful! Come again!").show();
});
return false; // prevent forms from submitting by default});Copy the code
This method relies too much on the library and can be very expensive on the mobile side, so FormData is better. FormData is also new to H5
==FormData can add a user-selected HTML file type input or JavaScript file-like object == or directly attach a file or Blob file to the FormData object, as shown below:
data.append("myfile", myBlob, "filename.txt");
Copy the code
Create a FormData object from Html elements
<! DOCTYPE html> <html> <head> <title></title> </head> <body> <form action="">
<label for=""> Name: <inputtype="text" name="name">
</label>
<label for=""> file: <input id="file" type="file" name="file">
</label>
<label for="">
<input type="button" value="Save">
</label>
<div class="progress"></div>
</form>
<script>
var btn = document.querySelector('[type=button]');
var progress = document.querySelector('.progress')
btn.onclick = function() {// file element var file = document.querySelector('[type=file]'); Var FormData = new FormData(); // Convert the file to binary formdata.append ('upload', file.files[0]); // JavaScript file-like object var content ='hey! '; // The body of the new file... var blob = new Blob([content], {type: "text/xml"});
formData.append("webmasterfile", blob);
var xhr = new XMLHttpRequest;
xhr.open('post'.'./file.php'); // Listen for upload progress xhr.upload.onprogress =function(ev) {// event object // console.log(ev); var percent = (ev.loaded / ev.total) * 100 +The '%';
console.log(percent);
progress.style.width = percent;
}
xhr.send(formData);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
//
}
}
}
</script>
</body>
Copy the code
Create a FormData object using Html Form elements and submit it using Ajax.
<! DOCTYPE html> <html> <head> <title></title> </head> <body> <form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32"
maxlength="64"/><br/>
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32"/><br/>
<label>File to stash:</label>
<input type="file" name="file" required/>
<input type="submit" value="Stash the file!"/>
</form>
<script src="/ / cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<script>
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit'.function(ev) {ev.preventdefault () // Var fd = new FormData(document.querySelector()"form"));
fd.append("CustomField"."This is some extra data");
$.ajax({
url: "./file.php".type: "POST",
data: fd,
processData: false// Do not process data contentType:false// do not set the content type}); }) </script> </body>Copy the code
The request header is: Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryVXQzCH5gOtjud1Xu
“– WebKitFormBoundary” plus a 16-bit random Base64-bit encoded string as the delimiter boundary
3. Upload using ANTD-Mobile ImagePicker + Fetch
import { ImagePicker, WingBlank, SegmentedControl } from 'antd-mobile';
const data = [{
url: 'https://zos.alipayobjects.com/rmsportal/PZUUCKTRIHWiZSY.jpeg',
id: '2121',
}, {
url: 'https://zos.alipayobjects.com/rmsportal/hqQWgTXdrlmVVYi.jpeg',
id: '2122',}];export default class ImagePickerExample extends React.Component {
state = {
files: data,
multiple: false,
}
onImageChange = (files, type, index) => {
if (type= ='add') {
var file = files[files.length - 1].file
let formData = new FormData();
formData.append("file", file);
files[files.length - 1].url = '.. /.. /.. /.. /src/white.png'
this.setState({files})
fetch('./file.php', {
method: 'POST',
headers: {},
body: formData,
}).then((response) => response.json()).then((res)=> {
if (res.code == 200) {
files[files.length - 1].url = res.value.fileUrl
}
this.setState({files},function () {
const dom = document.querySelectorAll('.am-image-picker-item')
dom[files.length - 1].className +=' now'
});
}).catch((err)=> {
util.showWarning(err)
});
} else{ this.setState({files}); }}render() {
const { files } = this.state;
return (
<div>
<ImagePicker
files={files}
onChange={this.onImageChange}
onImageClick={(index, fs) => console.log(index, fs)}
selectable={files.length < 3}
multiple={false} /> </div> ); }}Copy the code
The onImageChange files callback is triggered by a change in the value of the onImageChange files. The operationType operationType is add, remove, and if it is remove, the third parameter represents the index to remove the image
If type== ‘add’, upload the image. Since it is set to a single upload, the last data in the files array is the newly added file that needs to be uploaded
var file = files[files.length - 1].file
Copy the code
Use FormData to encapsulate the data
let formData = new FormData();
formData.append("file", file);
Copy the code
Since uploading takes time, in order to enhance user experience, the address is replaced with a transparent PNG image booth to show loading
files[files.length - 1].url = '.. /.. /.. /.. /src/white.png'
this.setState({files})
Copy the code
Note that when the fetch method is used, the header is not set and the wrapped formData is passed directly to the body
fetch('./file.php', {
method: 'POST',
headers: {},
body: formData,
})
Copy the code
Native mobile upload a reference great god: segmentfault.com/a/119000001…