【问题标题】:Web API Upload FilesWeb API 上传文件
【发布时间】:2016-12-20 20:08:38
【问题描述】:

我有一些数据要保存到数据库中。 我创建了一个 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”行时,它会将我带到它的方法。 从文件行开始,它跳过其余行并转到最后一行;什么意思它没有看到任何文件。 我能够将所有内容保存到数据库中,只是我没有在指定位置看到物理文件。 任何帮助将不胜感激。

问候,

索玛德

【问题讨论】:

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


    【解决方案1】:

    确保请求“content-type”:“multipart/form-data”已设置

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

    【讨论】:

      猜你喜欢
      • 2020-07-10
      • 2014-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-28
      • 2011-09-04
      • 2016-11-14
      • 1970-01-01
      相关资源
      最近更新 更多