Web API上载文件

时间:2016-11-11 11:58:01

标签: c# asp.net-web-api

我有一些数据要保存到数据库中。 我创建了一个web api post方法来保存数据。以下是我的帖子方法:

    [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();
    }

有一个名为'szAttachedDocumentNo'的字段,它也是一个保存在数据库中的文档。

保存所有数据后,我希望将'szAttachedDocumentNo'的物理文件保存在服务器上。所以我创建了一个名为“UploadFile”的方法,如下所示:

    [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);
            }
        }
    }

在运行项目之前,我对post方法进行了调试,所以当涉及到“UploadFile”行时,它会转到我的方法。 从文件行,它跳过剩余的行并转到最后一行;什么意思是它没有看到任何文件。 我能够将所有内容保存到数据库中,只是我没有在指定位置看到物理文件。 任何帮助将不胜感激。

问候,

Somad

1 个答案:

答案 0 :(得分:0)

确认请求&#34;内容类型&#34;:&#34; multipart / form-data&#34;已设置

            [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);
                }
            }