Using Jquery and HTML5 for File Upload

Source: Internet
Author: User

Using Jquery and HTML5 for File Upload

This article describes how to use Jquery to use the FormData attribute of HTML5 to upload files. It is very practical. If you need it, you can refer to it.

1. Use the FormData attribute of HTML5 in Jquery to upload files.

Before HTML5, if we need to implement functions such as file upload server, sometimes we have to rely on FLASH for implementation. After HTML5 comes, we can easily upload files, you only need to use a FormData attribute of HTML5 and Jquery to Easily upload files and read the file upload progress. The following upload case is based on the above implementation, below I will put all JS, CSS and HTML page code below.

Note: The FormData attribute must depend on HTML5. Therefore, if you follow the functions implemented in the code in this article, the browser must be updated to the latest version (HTML5 FormData attribute is supported ).

2. the HTML page code is as follows:

?

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

<! DOCTYPE html>

 

<Html lang = "en" xmlns = "http://www.w3.org/1999/xhtml">

<Head>

<Meta charset = "UTF-8"/>

<Title> use the FormData attribute of HTML to upload a file </title>

<Link rel = "stylesheet" href = "../css/fileUpload.css"/>

</Head>

<Body>

<Table id = "uploadTable" style = "border: 1px;"> </table>

<Br/>

<A href = "javascript: void (0);" class = "input-file">

Add a file <input type = "file" id = "txtFile" style = "width: 200px;"/>

</A>

<Script type = "text/javascript" src = ".../js/jquery-1.7.1-min.js"> </script>

 

<Script type = "text/javascript">

$ (Function (){

$ ('# UploadTable'). SalesMOUNDUpload ({

SaveUrl: '/Test/save ',

JqInput: $ ('# txtFile '),

FnRemove: removeFile,

FnComplete: function (d ){

Window. console. log ('complete' + d );

}

});

});

Function removeFile (d ){

$. Post ('/Test/delete', {"filename": d}, function (r ){

 

});

}

</Script>

</Body>

</Html>

3. the CSS code is as follows:

?

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

/* Source file header information:

<Copyright file = "FileUpload. js">

Copyright (c) 2014-2034 Kencery. All rights reserved.

Blog: http://www.cnblogs.com/hanyinglong

Created by: kencery)

Created on:

</Copyright> */

 

Body

{

Font-family: "";

Font-size: 12px;

}

. Input-file {

Overflow: hidden;

Position: relative;

}

. Input-file input {

Opacity: 0;

Filter: alpha (opacity = 0 );

Font-size: 100px;

Position: absolute;

Top: 0;

Right: 0;

}

# UploadTable {

Width: 500px;

Border-collapse: collapse;

Border: 1px solid Silver;

}

4. The JS Code is as follows:

?

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

// Source file header information:

// <Copyright file = "FileUpload. js">

// Copyright (c) 2014-2034 Kencery. All rights reserved.

// Created by: kencery)

// Creation Time:

// </Copyright>

;

(Function ($ ){

$. Fn. SalesMOUNDUpload = function (options ){

Var defaults =

{

SaveUrl :'',

JqInput :'',

MaxSize: 1024*1024*100, // 100 M

FnRemove: '', // remove a file, parameter: File Name

FnComplete: ''// each file succeeded. Parameter: Content returned by the server

};

Var opt = $. extend (defaults, options );

Function getByteToM (val ){

If (isNaN (val) return val;

Val = val/(1024*1024 );

Val = Math. round (val * 100)/100;

Return val;

}

Return this. each (function (){

Var $ this = $ (this );

$ This. empty ();

If (typeof FormData = 'undefine '){

Alert ('The browser version is too low and cannot be uploaded! ');

Return;

}

// Header

If ($ this. find ('thead'). length = 0 ){

Var $ thead = $ ('<thead> ');

Var $ th_tr = $ ('<tr> ');

$ Th_tr.append ('<th> file name </th> ');

$ Th_tr.append ('<th> type </th> ');

$ Th_tr.append ('<th> size </th> ');

$ Th_tr.append ('<th> Status </th> ');

$ Th_tr.append ('<th> operation </th> ');

$ Th_tr.appendTo ($ thead );

$ This. append ($ thead );

}

Opt. jqInput [0]. addEventListener ('change', function (e ){

Var file = this. files [0];

If (! File ){

Return;

}

If (file. size> opt. maxSize ){

Window. alert ('file exceeds Max ');

Return;

}

Var fd = new FormData ();

Var $ table = $ this;

Fd. append ("uploadFile", file );

Var xhr = new XMLHttpRequest ();

Xhr. open ('post', opt. saveUrl, true );

Xhr. upload. addEventListener ("progress", uploadProgress, false );

Xhr. addEventListener ("load", uploadComplete, false );

Xhr. addEventListener ("error", uploadFailed, false );

Xhr. addEventListener ("abort", uploadCanceled, false );

// Table content

Var $ tr = $ ('<tr> ');

$ Tr. append ('<td class = "upload_name">' + file. name + '</td> ');

$ Tr. append ('<td class = "upload_type">' + file. type + '</td> ');

$ Tr. append ('<td class = "upload_size">' + getByteToM (file. size) + 'M' + '</td> ');

$ Tr. append ('<td class = "upload_status">' + 0 + '</td> ');

$ Tr. append ('<td class = "upload_action"> <a href = "javascript: void (0 ); "> '+' cancel '+' </a> </td> ');

$ Tr. find ('. upload_action A'). unbind ('click'). bind ('click', function (){

Xhr. abort ();

});

$ Table. append ($ tr );

Function uploadProgress (evt ){

If (evt. lengthComputable ){

Var percentComplete = Math. round (evt. loaded * 100/evt. total );

Required tr.find('.upload_status'0000.html (Math. round (percentComplete) + '% ');

} Else {

Fig fig ('unable to compute ');

}

}

Function uploadComplete (evt ){

If (evt.tar get. status = 200 ){

Export tr.find('.upload_status'finished .html ('finished ');

$ Tr. find ('. upload_action a'hangzhou.html ('delete ');

If (typeof opt. fnComplete = 'function '){

Opt.fnComplete(evt.tar get. response );

}

$ Tr. find ('. upload_action'). unbind ('click'). bind ('click', removeFile );

}

}

Function uploadFailed (){

Fig fig ('<a href = "javascript: void (0);"> × </a> ');

$ Tr. find ('. upload_status A'). unbind ('click'). bind ('click', function (){

$ Tr. remove ();

});

$ Tr. find ('. upload_action a'hangzhou.html ('retried ');

$ Tr. find ('. upload_action A'). unbind ('click'). bind ('click', function (){

Xhr. send (fd );

});

}

Function uploadCanceled (){

$ Tr. remove ();

}

Function removeFile (){

$ Tr. remove ();

If (typeof opt. fnRemove = 'function '){

Opt. fnRemove (file. name );

}

}

Xhr. send (fd );

}, False );

});

};

} (JQuery ));

5. Code Viewing address: https://github.com/kencery/Common/tree/master/KenceryCommonMethod/%E6%96%87%E4%BB%B6%E4%B8%8A%

E4 % BC % A0

The above is all the content of this article. I hope you will like it.

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.