Java File Upload

Source: Internet
Author: User

This article is reproduced from file upload and Angular

Recent projects need to use Angular, for beginners Angular I can only bite the bullet, the project has a need is file upload, stumbled also realized, will realize the process of learning some knowledge recorded for future inspection.

Knowledge related to form data encoding

In general, we use HTML tags <form> to create a form for user input, using a <input type="file"> control that is uploaded as a file.

To send data from a form to the background, you need to determine not only the <form> HTTP method for sending the data through the specified property, method but also the encoding of the sending data through the specified <form> properties enctype .

These two properties are briefly described below.

Properties of Form formmethod

<form>The method Form-data property specifies the HTTP method used to send the message, and its value can be get either post . The request will be get sent after the form's data is encoded in name1=value1&name2=value2 the form appended to the requested URL. postthe request encodes the form's data and sends it into the request body.

The next discussion in this article is primarily based on the post request method.

Properties of Form formenctype

<form>The properties of a label are entype used to specify how the form data should be encoded before it is sent, in effect specifying the type of encoding requested.

enctypeThe W3school property has 3 values, and its value is described in the following:

Take value Description
application/x-www-form-urlencoded Spaces converted to "+" plus, special symbols converted to ASCII HEX values
Multipart/form-data Character encoding is not. You must use this value when you use a form that contains a file upload control
Text/plain Spaces are converted to "+" plus signs, but special characters are not encoded

application/x-www-form-urlencodedThis is the default way of encoding, if the form is <form> useful to the file upload control, it is necessary to manually specify the encoding multipart/form-data .

The following are examples of these types of coding methods (both based on the post request method)

    • Code for application/x-www-form-urlencoded the case

First, construct a form:

<form method="post" action="/" enctype="application/x-www-form-urlencoded">  <input type="text" name="name1" placeholder="name1">  <input type="text" name="name2" placeholder="name2">  <input type="submit"></form>

Input in the input box i‘m name1 and [email protected] , according to the Code rules, when the form is submitted, the form data will be encoded into the name1=i%27m+name1&name2=name%402 request body to pass, the chrome results are executed in the browser as expected.


Toapplication/x-www-form-urlencodedEncode the form data to send
    • Code for multipart/form-data the case

The coding is multipart/form-data different, so let's look at the results of the sample code.

Example code:

<form method="post" action="/" enctype="multipart/form-data">  <input type="text" name="name1" placeholder="name1">  <input type="text" name="name2" placeholder="name2">  <input type="file" name="inputfile">  <input type="submit"></form>

Enter and in the input box i‘m name1 [email protected] , and then select a file named Testfile.txt upload, you can see in the chrome send request as follows:


Tomultipart/form-dataEncode the form data to send

Note the red box in the picture, the Content-Type value of multipart/form-data; boundary=----WebKitFormBoundaryBdpfgMg4VKAZat6C which is a field called, which is a boundary randomly generated by the browser string, as the form of data segmentation boundary to use, on the server side will be based on this boundary boundary field to parse the form data.

It can be seen that each segment of the boundary is corresponding to a form data, each item contains a Content-Disposition field and a name field, and for the uploaded file there is one more attribute to specify the name of the uploaded file and a field for the filename type of upload file Content-Type . As the example of the uploaded file is the .txt format of the file, so Content-Type the value of the text/plain file extension and Content-Type the table can be seen here.

    • Code for text/plain the case
      This is application/x-www-form-urlencoded similar to the case of encoding, where the only difference is that text/plain special characters are not encoded.
The Angular implementation of file uploads is based onFormDataThe implementation

Implementation of the idea: through the File API acquisition of files uploaded in the control, the use of FormData types to construct form data upload.

Basic knowledge:File APIAndFormData 类型
    • File API

File API(File API) provides a secure way for Web developers to access files on a user's computer and perform operations on those files better.

Specifically, File API in the form of the file input field based on the addition of some direct access to file information interface. HTML5 DOM A collection has been added to the file INPUT element in files . When one or more files are selected through a File entry field, the files collection contains a set File of objects, each of which File corresponds to a file.

Constructs a file upload form, with the following jQuery code:

$("input[type=‘file‘]")[0].files

chromeyou can see the following information in the browser console:

You can see information about the selected file testfile.txt , so you can get the uploaded file in the above way.

File APImore about the narrative can be obtained here.

    • FormDataType

FormDatais XMLHttpRequest Level 2 defined in, which facilitates the serialization of forms and the creation of the same data as the form format (for transmission via XHR).

The following is a FormData description of the object referenced from the MDN, and more on FormData the type of narrative can be obtained here.

XMLHttpRequest Level 2 Adds a new interface FormData. Using the Formdata object, we can simulate a series of form controls using JavaScript with some key-value pairs, and we can use the XMLHttpRequest Send () method to asynchronously submit the form. The biggest advantage of using FormData compared to normal Ajax is that we can upload a binary file asynchronously.

As can be seen, we could use FormData objects to simulate the form data that was submitted when the file was uploaded, and the construction of the submitted data was FormData implemented by means of a method that append() FormData adds a key/value pair to the current object.

Angular implementation

With the implementation ideas and basic knowledge mentioned above, it is now possible to proceed with the implementation of the Code.

    • First, write an instruction to get the object to upload the file File .

The code is as follows:

. directive ("Filemodel", ["$parse",function$parse) { return { restrict: ' A ', Link: function ( scope, element, attrs) { var model = $parse (attrs.f Ilemodel); var modelsetter = model.assign; Element.bind ( "Change", function () {scope. $apply ( function ( ) {Modelsetter (scope, element[0].files[0]); //Console.log (scope);} ) } ) } }}])

This instruction is used in the following ways:

<input type="file" file-model="fileToUpload">

For <input> elements, events are triggered when they lose focus and value changes, change so we listen for events on the element in the function of the instruction, link change get the file information uploaded by the user in the event response function, and assign the file to the $scope object and the instruction c6/> the properties of the binding (in the example above fileToUpload ).

You can run the code in the example, select a file filetest.txt , and print out the assigned $scope object as follows:


Assigns the acquired upload file to the$scopeObject

As shown in the red box, the $scope property is the information for the fileToUpload uploaded file filetest.txt .

    • Then, write a service to send a request to upload the file multipart/form-data .

The code is as follows:

. Service ("FileUpload", ["$http",function$http) { This.uploadfiletourl = function ( file, uploadurl) { var fd = new FormData (); Fd.append ( "file", File) $http. Post (Uploadurl, FD, { transformRequest:angular.identity, headers: { "Content-type": unde Fined}). Success (function () { //BlaBla ...}). Error ( function () { //BlaBla ...})}]) 

In the method of the service fileUpload uploadFileToUrl , FormData The append() method is used to serialize the uploaded file into form data and then send it to the background by means of the method $http.post() .

Angular the default transformRequest method will attempt to serialize our FormData object, so here we use angular.identity the function to overwrite it, and Angular to use the default when sending a POST request Content-Type application/json , so here we need to adjust to undefined , the browser will automatically help us to set multipart/form-data the encoding method, but also generate a suitable boundary , if manually set multipart/form-data to the words will not generate the boundary field.

    • Finally, send this request at the appropriate place in the controller.

Now that we've got the information about the uploaded file and a service for sending it, just define a function for sending in the controller and then call it at the right time to upload the file to the background.

For example, $scope define a function to send the request inside the controller sendFile :

"myCtrl", [ "$scope", "fileUpload", function( $scope, fileUpload ){ $scope.sendFile = function(){ var url = "/server", file = $scope.fileToUpload; if ( !file ) return; fileUpload.uploadFileToUrl( file, url ); }}])

Then we can define a button that will send the uploaded file when the user clicks on the button.

<button type="button" ng-click="sendFile()">Submit</button>

The result is this:


PassFormDataRequest compatibility for uploading files

Because it is FormData compatible with ie10+ only, the above method is only available in ie10+.

If your application needs to be compatible with IE8, be sure to encapsulate an iframe-containing instruction, and then look down.

Implementations that contain an IFRAME

The instruction code is as follows

. directive ("Iframefileupload", [function){var inner ="<div>"; Inner + ="<form action=\"/server\ "method=\" post\ "enctype=\" multipart/form-data\ "target=\" uploadiframe\ ">"; Inner + ="<input type=\" file\ "name=\" filename\ ">"; Inner + ="<input type=\" submit\ ">"; inner + = "</form>" inner + = "<iframe id=\" uploadiframe\ "name=\" Uploadiframe\ "style=\" display:none\ "></iframe>"; Inner + = "</div>"; return{ Restrict: "A", Template:inner, //or /templateurl: "components/iframefileupload.html ", replace: true, scope: {}, Link: function ( scope, element, attrs) { //BlaBla ...}}]) 

This is probably the way it is called:

<div iframe-file-upload></div>

Java File Upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.