Welcome to the next part of tutorial in Web API series. In this post, I am going to explain, how to upload the files, using Web API help of jquery. If you are new to Web API in ASP.NET MVC5. Refer below the posts for the basics of Web API.
- Introduction to Web API.
- How to retrieve and display the data from Web API in ASP.NET MVC5.
- How to post the data to Web API, using jQuery client.
Create an API Service to save the uploaded file in the Server
- I created a UploadapiController API controller.
- Add a new folder "UploadFiles" folder to the solution.
- Replace the UploadapiControlller code with the code, given below, to save the uploaded file.
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Threading.Tasks;
- using System.Web;
- using System.Web.Http;
- namespace WebApiExample.Controllers {
- public class UploadapiController: ApiController {
- public Task Post() {
- List savedFilePath = new List();
- if (!Request.Content.IsMimeMultipartContent()) {
- throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
- }
- string rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
- var provider = new MultipartFileStreamProvider(rootPath);
- var task = Request.Content.ReadAsMultipartAsync(provider).
- ContinueWith(t => {
- if (t.IsCanceled || t.IsFaulted) {
- Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
- }
- foreach(MultipartFileData item in provider.FileData) {
- try {
- string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
- string newFileName = Guid.NewGuid() + Path.GetExtension(name);
- File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
- Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
- string fileRelativePath = "~/UploadedFiles/" + newFileName;
- Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
- savedFilePath.Add(fileFullPath.ToString());
- } catch (Exception ex) {
- string message = ex.Message;
- }
- }
- return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
- });
- return task;
- }
- }
- }
Add Controller to display the Index(Fileupload element)



inco bilgisayarPosted Sep 2, 2018, 1:39 PM
Is there any sample with webservices(.net), jquery(ajax) and mssql