Form upload
This is the traditional form of form upload, use form form input [type = "file"] control, you can open the system file selection dialog box, so as to achieve the purpose of selecting files and upload, it is multi-browser compatible, it is Is the most commonly used web developers a way to upload files.
The form code is as follows:
<form method="post" action="http://uploadUrl" enctype="multipart/form-data">
<input name="file" type="file" accept="image/gif,image.jpg" />
<input name="token" type="hidden" />
<input type="submit" value="submit" />
</form>
Here are a few key points for the form upload:
method = "post": Submit data using post method
enctype = "multipart / form-data": The multipart format upload file, the request header will display Content-Type: multipart / form-data; boundary = ---- WebKitFormBoundaryzr34cwJ67R95KQC9
action: indicates the address of the server to upload
type = "file": Use input file control upload
If it is a multi-file bulk upload, you can set the name property of input [type = "file"] to something like: name = "file []"
The accept property is a new HTML5 property that specifies the types of files that can be submitted via file upload
The trigger for the upload can be: onchange triggered by input [type = "file"], or by a separate button onclick to commit the entire form, with input [type = "hidden"] and some other Parameters, such as Token source verification and more.
2 Ajax no refresh upload
Ajax no way to refresh the upload, essentially the same as the form upload, just submit the contents of the form submitted by ajax, and the front-end request results after the return of the display results, do not like direct form upload as refresh and jump page. Here, we use jQuery as the base for manipulating the DOM and creating js submitted by ajax.
html code fragment is as follows:
<form>
<input id="file" name="file" type="file" />
<input id="token" name="token" type="hidden" />
</form>
javascript code snippet is as follows:
$("#file").on("change", function(){
var formData = new FormData();
formData.append("file", $("#file")[0].files);
formData.append("token", $("#token").val());
$.ajax({
url: "http://uploadUrl",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(response){
// According to the return result to specify the interface operation
}
});
});
We use the file control change to trigger the upload event, of course, you can also use a button to trigger the form to submit. When submitting the data, I used the FormData object to send the binary file. The append () method provided by the FormData constructor can be added to the server as an XMLHttpRequest instance parameter with some additional parameters attached directly to the binary file.
Using the ajax method provided by jQuery to send a binary file requires the addition of two parameters:
processdata: false / / Do not serialize the data parameter, the default is true
contentType: false / / Do not set the Content-Type request header, because the file data is encoded as multipart / form-data
Ajax upload can refer to the site article: PHP + jQuery + Ajax multiple image upload
Flash upload
Many times the demand for upload shows the progress of the upload, interrupt the upload process, upload large file fragments, etc., then the traditional form upload is difficult to achieve these features, resulting in the use of Flash upload method, which uses Flash as an intermediate agent Layer, instead of client to server communication, in addition, it also has more control over the client's file selection than the input [type = "file"] is much larger.
Here I use the jQuery packaged uploadify plug-in to demonstrate, the general type of plug-in comes with the upload Flash file, because the data returned with the server and display with the client's interaction, are Flash file interface Docking to docking.
<div id="file_upload"></div>
html part is very simple, set aside a hook, the plug-in will create a Flash object within this node, and also with the creation of the upload progress, cancel the control and multi-file queue display interface.
$(function() {
$("#file_upload").uploadify({
auto: true,
method: "Post",
width: 120,
height: 30,
swf: './uploadify.swf',
uploader: 'http://uploadUrl',
formData: {
token: $("#token").val()
},
fileObjName: "file",
onUploadSuccess: function(file, data, response){
//According to the return result to specify the interface operation
}
});
});
About jQuery.uploadify You can visit: . It is noteworthy that the flash is not suitable for mobile applications, a better solution is to use flash + html5 to solve the compatibility issue of the platform.
Screenshot paste upload
We found that there are a lot of upload applications have been provided screenshot paste upload function, such as WebUploader, it supports QQ screenshot and then paste the upload.
First of all, the core idea of the screenshot paste upload is to monitor the paste event, and then get the data in the clipboard, if it is a picture, the upload event is triggered.
The code snippet is as follows:
$("textarea").on("paste", function(e){
e.stopPropagation();
var self = this;
var clipboardData = e.originalEvent.clipboardData;
if (clipboardData.items.length <= 0) {
return;
}
var file = clipboardData.items[0].getAsFile();
if (!file) {
return;
}
var formData = new FormData();
formData.append("file", file);
formData.append("token", $("#token").val());
$.ajax({
url: "http://uploadUrl",
type: "POST",
data: formData,
}).done(function(response) {
// operation by ur idea
});
e.preventDefault();
});
As can be seen from the above code, the upload process is the same, mainly to obtain the file. When paste (right paste / ctrl + v) operation, trigger the clipboard event 'paste', get the contents from the system clipboard, and system clipboard data stored in different browser in different locations:
IE kernel: windows.clipboardData
Other: e.originalEvent.clipboardData
You can read Image upload and clipping applications by Croppie to learn the method.
Drag and drop upload
Drag-and-drop method, support fewer browsers, because it uses two new HTML5 attributes (API) a Drag and Drop, a File API.
Upload domain monitoring drag and drop three events: dragEnter, dragOver and drop, respectively, corresponding to the drag and drop, drag and release of the three operating mechanism, of course, you can also monitor the dragLeave event.
HTML5 File API provides a FileList interface, it can drag the event e.dataTransfer.files to pass the file information for local file list information.
The File API is just a draft in the HTML5 specification. In the W3C draft, a File object contains only read-only attributes such as file name, file type, and file size. However, some browsers provide an object named FileReader outside the draft to read the contents of the file and monitor the read status. The methods it provides are readAsBinaryString, readAsDataURL, readAsText, "abort" and so on.
The code snippet is as follows:
// dragenter
$("#textarea").on("dragenter", function(e){
e.preventDefault();
});
// dragover
$("#textarea").on("dragover", function(e){
e.preventDefault();
});
// drop
$("#textarea").on("drop", function(e){
e.stopPropagation();
e.preventDefault();
var files = e.originalEvent.dataTransfer.files;
_.each(files, function(file) {
if (!/^image*/.test(file.type)) {
return;
}
var fileReader = new FileReader();
fileReader.onload = function() {
//uploadFile(file);
};
fileReader.readAsDataURL(file);
});
});
Drag and drop a few key points in the upload process:
After the drop event is triggered by e.dataTransfer.files get a list of drag files in jQuery e.originalEvent.dataTransfer.files
Drag-and-drop upload only supports images, and file.type in the file object identifies the file type.
Since it may be multi-image drag and drop, so you can traverse the image upload, use Underscore each method.
Here readAsDataURL reads the contents of the file as a binary file, you can also convert it to Base64 upload method, but there is http protocol inside non-binary data upload size limit of 2M.
The process of uploading is the same as before, ie creating a FormData object and initiating an Ajax request.
Upload photos
Camera upload can be a camera on a PC Camera upload can also be mobile phones and other mobile device photo upload. The most common photo upload on mobile phones is that we use WeChat to send photos.
Phone to achieve photo upload code:
<input type=file accept="image/*">
<input type=file accept="video/*">
ios have pictures, videos, select the local image features, select only part of the android local image features.
Upload and security
File upload must be done file security, in addition to the front of the necessary validation, such as file type, suffix, size and other validation, the important thing is to do in the background security strategy.
Here I cite a few notes:
Background need to document type, size, source verification
Define an .htaccess file that will only allow access to the file with the specified extension.
Generate a random file name for the uploaded file, plus the previously generated file name extension.
Set the upload directory permissions to prevent malicious people bypassing the image extension of malicious attacks, the possibility of rejecting script execution.