Upload file using WebApi, ajax

后端 未结 6 1179
深忆病人
深忆病人 2020-12-06 02:39

I want to upload file using a WebApi by making an ajax call and the file will save into database. I tried the code given in the this link. Here, it is saved the received da

6条回答
  •  没有蜡笔的小新
    2020-12-06 03:44

    A cleaner way to do this using webAPI controller is as follows:

    Create a web api controller file: UploadFileController.cs

    public class UploadFileController : ApiController
    {
        // POST api/
        public HttpResponseMessage Post()
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    int hasheddate = DateTime.Now.GetHashCode();
                    //Good to use an updated name always, since many can use the same file name to upload.
                    string changed_name = hasheddate.ToString() + "_" + postedFile.FileName;
    
                    var filePath = HttpContext.Current.Server.MapPath("~/Images/" + changed_name);
                    postedFile.SaveAs(filePath); // save the file to a folder "Images" in the root of your app
    
                    changed_name = @"~\Images\" + changed_name; //store this complete path to database
                    docfiles.Add(changed_name);
    
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
            else
            {
                result = Request.CreateResponse(HttpStatusCode.BadRequest);
            }
    
            return result;
        }
    }
    

    To use this webAPI in your markup. Use following:

    
    
    
    
                                     
                  
提交回复
热议问题