📜 ⬆️ ⬇️

Screwing ajax file uploads in asp.net mvc using jQuery plugins

In this article we will figure out how to dynamically load files into asp.net mvc using jQuery , its plug-ins, and such and such mother. For this we will do the “proof of concept” and try to enjoy the process. =)

To implement the conceived there are lots of options. I will focus on two plugins: Ajax upload and Multiple File Upload .


Part One: Server Side


On the server, everything is trivial. We will receive files from Request.Files . We communicate with client scripts via JSON. For this, the return value in the controller will be JsonResult , or its heirs. But the content type is text / html, otherwise browsers will offer to save the content like application / json.
')
Simple Action:
  1. private readonly IFileService _fileService = new FileServiceStub ( ) ;
  2. /// <summary>
  3. /// Processing upload files to the server.
  4. /// </ summary>
  5. /// <returns> Json Result containing the list of file names. </ returns>
  6. [ HttpPost ]
  7. public JsonResult UploadFiles ( )
  8. {
  9. ICollection < string > collection = _fileService. Upload ( Request. Files ) ;
  10. return new JsonResult
  11. {
  12. ContentType = "text / html" ,
  13. Data = new { collection }
  14. } ;
  15. }


Part Two: Multiple File Upload Plugin


This plugin works together with jQuery.Form .

Html form:
  1. < form id = "upload-files" action = "/ File / UploadFiles" method = "post" enctype = "multipart / form-data" >
  2. < div >
  3. Upload files:
  4. < input class = "multi-file-upload" type = "file" name = "file" / > < / div >
  5. < input type = "submit" value = "Download" > < / input >
  6. < / form >
  7. <! - Download message output location ->
  8. < div id = "messages" > < / div >
  9. < h3 > List of uploaded files < / h3 >
  10. < ol id = "file-list" > < / ol >


Plugin configuration:
  1. // Executes the code when the document is fully loaded.
  2. $ ( document ) . ready ( function ( ) {
  3. var form = $ ( '# upload-files' ) ; // Download form.
  4. var messages = $ ( '#messages' ) ; // The notification area.
  5. var list = $ ( '# file-list' ) ; // List of files already uploaded.
  6. // Configure MultiFile.
  7. $ ( '.multi-file-upload' ) . MultiFile ( {
  8. max : 5 , // Number of files uploaded at once.
  9. STRING : { // String Translation. You can insert html-code (pictures, for example).
  10. remove : 'Remove' ,
  11. Selected : 'Selected: $ file' ,
  12. denied : 'Invalid extension: $ ext!' ,
  13. duplicate : 'This file is already selected: \ n $ file!'
  14. }
  15. } ) ;
  16. // Set up ajaxForm
  17. form. ajaxForm ( {
  18. iframe : true , // Ship using iframe.
  19. dataType : "json" , // Exchange is conducted using json.
  20. // Perform before sending files.
  21. beforeSubmit : function ( ) {
  22. // Uncomment the next line, if submit is called from javascript.
  23. // $. fn.MultiFile.disableEmpty ();
  24. // Display a download message. It is better to tie jQuery.blockUI here, but I leave it for clarity.
  25. messages. html ( '<img src = "/ Content / busy.gif" /> Load file (s) ...' ) ;
  26. } ,
  27. // Execute after receiving a response about success.
  28. success : function ( result ) {
  29. // Uncomment the next line, if submit is called from javascript.
  30. // $. fn.MultiFile.reEnableEmpty ();
  31. // Clear the file upload form.
  32. $ ( '.multi-file-upload' ) . MultiFile ( 'reset' ) ;
  33. // Clear the boot message.
  34. messages. empty ( ) ;
  35. // Add new uploaded files to the general list of uploaded files.
  36. if ( result. collection . length > 0 ) {
  37. $. each ( result. collection , function ( i ) {
  38. list. append ( '<li>' + this + '</ li>' ) ;
  39. } ) ;
  40. }
  41. } ,
  42. // Execute on error.
  43. error : function ( xhr , textStatus , errorThrown ) {
  44. // Clear the file upload form.
  45. $ ( '.multi-file-upload' ) . MultiFile ( 'reset' ) ;
  46. alert ( 'An error occurred while loading files:' + errorThrown ) ;
  47. }
  48. } ) ;
  49. } ) ;


Part Three: Ajax Upload Plugin



Html form:
  1. <! - File upload form. May be arbitrary. ->
  2. < div id = "file_upload_button" >
  3. <a href = "#"> Add < / a > a new file. < / div >
  4. < div id = "uploading" style = "display: none" > < img src = "/Content/busy.gif" alt = "Download" align = "left" / > Loading. < / div >
  5. <! - List of downloaded files ->
  6. < ol class = "files" > < / ol >


Plugin configuration:
  1. $ ( document ) . ready ( function ( ) {
  2. new AjaxUpload ( $ ( '#file_upload_button' ) ,
  3. {
  4. // Whether to send the file immediately after selection
  5. autoSubmit : true
  6. // Where to send
  7. action : '/ File / UploadFiles' ,
  8. // Variable name to store the file.
  9. name : 'myfile' ,
  10. // Type of server response.
  11. response : 'json' ,
  12. // Fires before file upload
  13. // You can also return false to cancel.
  14. onSubmit : function ( file , extension ) {
  15. // Hide the file select button.
  16. $ ( '#file_upload_button' ) . hide ( ) ;
  17. // Show the download message.
  18. $ ( '#uploading' ) . show ( ) ;
  19. // If you need to load only one file:
  20. //this.disable ();
  21. } ,
  22. // Run after receiving a response from the server.
  23. // file is the name of the file specified by the client.
  24. // response - server response.
  25. onComplete : function ( file , response ) {
  26. $ ( '#file_upload_button' ) . show ( ) ;
  27. $ ( '#uploading' ) . hide ( ) ;
  28. // Get the javascript object.
  29. var resultObject = eval ( '(' + response + ')' ) ;
  30. // Add new uploaded files to the general list.
  31. if ( resultObject. collection . length > 0 ) {
  32. $. each ( resultObject. collection , function ( i ) {
  33. $ ( '.files' ) . append ( '<li>' + this + '</ li>' ) ;
  34. } ) ;
  35. }
  36. }
  37. } ) ;
  38. } ) ;

Instead of conclusion


MultiFile can send multiple files at once, but it is placed only in standard form ( <input type="file"... ). Size: MultiFile (~ 20Kb) + jQuery.Form (~ 22Kb) = ~ 42Kb.

AjaxUpload sends files one by one, but you can flexibly customize its presentation - it is not attached to the form. Plugin size: 14Kb, i.e. three times less than MultiFile + Form.

Both have a “restriction”: files are selected one by one. If you want to select several (tens) files at once, look towards the flash technology.

Sample sources are online. You can merge them entirely , but you can immediately see .

Source: https://habr.com/ru/post/70249/


All Articles