Upload files using jquery + Ajax in MVC

Source: Internet
Author: User

1. view page code

 

View code 1 <SCRIPT src = "http://www.cnblogs.com/Scripts/jquery.form.js" type = "text/JavaScript"> </SCRIPT>
2
3 <Form ID = "filepost" Action = "/home/upload" method = "Post" enctype = "multipart/form-Data">
4
5 <label> filename: <input type = "file" name = "file" onchange = "Save ();"/> </label>
6 <input id = "buttonupload" type = "Submit" value = "Upload"/>
7 </form>
8
9 <Div id = "outputdiv"> </Div

 

2. Controller page

 

View code 1 Public jsonresult upload (httppostedfilebase file)
2 {
3
4 If (file. contentlength = 0)
5 {
6 return json (New
7 {
8 Bret = false,
9 smsg = "select an image! "
10}, "text/html ");
11}
12 // upload the file code. Remember to create the upload folder first.
13 var filename = path. Combine (request. mappath ("~ /Upload "), path. getfilename (file. filename ));
14 try
15 {
16 file. saveas (filename );
17
18 return JSON (New
19 {
20 Bret = true,
21 smsg = "uploaded successfully"
22}, "text/html ");
23}
24 catch
25 {
26 return JSON (New
27 {
28 Bret = false,
29 smsg = "Upload Failed"
30}, "text/html ");
31}
32

 

3. Javascript

 

View code 1 function save (){
2 var Options = {
3
4 beforesubmit: showrequest,
5 error: showerror,
6 success: showresponse
7 };
8
9 $ ('# filepost'). ajaxsubmit (options );
10}
11
12 $ (document). Ready (function (){
13 var Options = {
14 target: '# outputdiv ',
15 beforesubmit: showrequest,
16 error: showerror,
17 success: showresponse
18 };
19 $ ('# filepost'). Submit (function (){
20 $ (this). ajaxsubmit (options );
21 return false;
22 });
23 });
24 function showrequest (formdata, jqform, options ){
25 alert ('before sending ');
26 return true;
27}
28 function showerror (data ){
29 alert ('error ');
30}
31
32 function showresponse (responsetext, statustext ){
33
34 alert (responsetext + "," + statustext + "," + 'Post send ');
35

 

4. Download jquery. Form. js

/Files/yso1983/jquery.form.rar

Related Article

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.