简体   繁体   中英

Web API Upload Files

I have some data to save into a database. I have created a web api post method to save data. Following is my post method:

    [Route("PostRequirementTypeProcessing")]
    public IEnumerable<NPAAddRequirementTypeProcessing> PostRequirementTypeProcessing(mdlAddAddRequirementTypeProcessing requTypeProcess)
     {
        mdlAddAddRequirementTypeProcessing rTyeProcessing = new mdlAddAddRequirementTypeProcessing(); 

        rTyeProcessing.szDescription = requTypeProcess.szDescription;
        rTyeProcessing.iRequirementTypeId = requTypeProcess.iRequirementTypeId;
        rTyeProcessing.szRequirementNumber = requTypeProcess.szRequirementNumber;
        rTyeProcessing.szRequirementIssuer = requTypeProcess.szRequirementIssuer;
        rTyeProcessing.szOrganization = requTypeProcess.szOrganization;
        rTyeProcessing.dIssuedate = requTypeProcess.dIssuedate;
        rTyeProcessing.dExpirydate = requTypeProcess.dExpirydate;
        rTyeProcessing.szSignedBy = requTypeProcess.szSignedBy;
        rTyeProcessing.szAttachedDocumentNo = requTypeProcess.szAttachedDocumentNo;
        if (String.IsNullOrEmpty(rTyeProcessing.szAttachedDocumentNo))
        {

        }
        else
        {
            UploadFile();
        }
        rTyeProcessing.szSubject = requTypeProcess.szSubject;
        rTyeProcessing.iApplicationDetailsId = requTypeProcess.iApplicationDetailsId;
        rTyeProcessing.iEmpId = requTypeProcess.iEmpId;

        NPAEntities context = new NPAEntities();
        Log.Debug("PostRequirementTypeProcessing Request traced");

        var newRTP = context.NPAAddRequirementTypeProcessing(requTypeProcess.szDescription, requTypeProcess.iRequirementTypeId, 
                                    requTypeProcess.szRequirementNumber, requTypeProcess.szRequirementIssuer, requTypeProcess.szOrganization, 
                                    requTypeProcess.dIssuedate, requTypeProcess.dExpirydate, requTypeProcess.szSignedBy, 
                                    requTypeProcess.szAttachedDocumentNo, requTypeProcess.szSubject, requTypeProcess.iApplicationDetailsId, 
                                    requTypeProcess.iEmpId);

        return newRTP.ToList();
    }

There is a field called 'szAttachedDocumentNo' which is a document that's being saved in the database as well.

After saving all data, I want the physical file of the 'szAttachedDocumentNo' to be saved on the server. So i created a method called "UploadFile" as follows:

    [HttpPost]
    public void UploadFile()
    {
        if (HttpContext.Current.Request.Files.AllKeys.Any())
        {
            // Get the uploaded file from the Files collection
            var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];

            if (httpPostedFile != null)
            {
                // Validate the uploaded image(optional)
                string folderPath = HttpContext.Current.Server.MapPath("~/UploadedFiles");
                //string folderPath1 = Convert.ToString(ConfigurationManager.AppSettings["DocPath"]);

                //Directory not exists then create new directory
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                // Get the complete file path
                var fileSavePath = Path.Combine(folderPath, httpPostedFile.FileName);

                // Save the uploaded file to "UploadedFiles" folder
                httpPostedFile.SaveAs(fileSavePath);
            }
        }
    }

Before running the project, i debbugged the post method, so when it comes to "UploadFile" line, it takes me to its method. From the file line, it skipped the remaining lines and went to the last line; what means it didn't see any file. I am able to save everything to the database, just that i didn't see the physical file in the specified location. Any help would be much appreciated.

Regards,

Somad

Makes sure the request "content-type": "multipart/form-data" is set

            [HttpPost()]
            public async Task<IHttpActionResult> UploadFile()
            {
                if (!Request.Content.IsMimeMultipartContent())
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

                try
                {
                    MultipartMemoryStreamProvider provider = new MultipartMemoryStreamProvider();

                    await Request.Content.ReadAsMultipartAsync(provider);

                    if (provider.Contents != null && provider.Contents.Count == 0)
                    {
                        return BadRequest("No files provided.");
                    }

                    foreach (HttpContent file in provider.Contents)
                    {
                        string filename = file.Headers.ContentDisposition.FileName.Trim('\"');

                        byte[] buffer = await file.ReadAsByteArrayAsync();

                        using (MemoryStream stream = new MemoryStream(buffer))
                        {
                           // save the file whereever you want 

                        }
                    }

                    return Ok("files Uploded");
                }
                catch (Exception ex)
                {
                    return InternalServerError(ex);
                }
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM