Advertisement
svetlai

Upload File Ajax - .NET web services

Nov 11th, 2015
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.34 KB | None | 0 0
  1. namespace Test.Controllers
  2. {
  3. using System.IO;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Http;
  7.  
  8. public class FileUploadController : ApiController
  9. {
  10. [HttpPost]
  11. public void UploadFile()
  12. {
  13. if (HttpContext.Current.Request.Files.AllKeys.Any())
  14. {
  15. // Get the uploaded image from the Files collection
  16. var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
  17.  
  18. if (httpPostedFile != null)
  19. {
  20. // Validate the uploaded image(optional)
  21.  
  22. // Get the complete file path
  23. var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
  24.  
  25. // Save the uploaded file to "UploadedFiles" folder
  26. httpPostedFile.SaveAs(fileSavePath);
  27. }
  28. }
  29. }
  30. }
  31. }
  32.  
  33. <form id="register-user">
  34. <label for="fileUpload">
  35. Select File to Upload:
  36. </label>
  37. <input id="fileUpload" type="file" />
  38. <input id="btnUploadFile" type="submit" value="Upload File" />
  39. </form>
  40.  
  41. <script type="text/javascript">
  42. $(document).ready(function () {
  43.  
  44. $('#register-user').submit(function () {
  45. console.log('in submit')
  46. var data = new FormData();
  47.  
  48. var files = $("#fileUpload").get(0).files;
  49.  
  50. // Add the uploaded image content to the form data collection
  51. if (files.length > 0) {
  52. data.append("UploadedImage", files[0]);
  53. }
  54.  
  55. // Make Ajax request with the contentType = false, and procesDate = false
  56. var ajaxRequest = $.ajax({
  57. type: "POST",
  58. url: "http://localhost:63362/api/fileupload/uploadfile",
  59. contentType: false,
  60. processData: false,
  61. data: data
  62. });
  63.  
  64. ajaxRequest.done(function (xhr, textStatus) {
  65. // Do other operation
  66. });
  67. });
  68. });
  69. </script>
  70. //http://www.codeproject.com/Articles/806075/File-Upload-using-jQuery-AJAX-in-ASP-NET-Web-API
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement