2015-11-05 72 views
0

我有一个需要接受文件的API方法。我使用Postman Chrome插件来调用api并附加一个文件。HttpPostedFileBase不接受文件

在创建初始MVC网站后,我在我的MVC项目中添加了API功能。不知道我是否错过了一些配置,但是我的其他API调用只是在没有获取任何文件的情况下工作。

下面的代码

[Route("~/api/mediaitems/{token}/{eventId}")] 
    public async Task<HttpResponseMessage> MediaItems(string token, int eventId, HttpPostedFileBase upload) 
    { 
     if (upload.ContentLength > 0) 
     { 
      string _targetFolder = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["FilePath"]); 
      string _targetPath = Path.Combine(_targetFolder, Guid.NewGuid() + Path.GetFileName(upload.FileName)); 
      upload.SaveAs(_targetPath); 

      var mediaItem = new MediaItem 
      { 
       MediaFilePath = _targetPath, 
       FileType = upload.FileName, 
       EventId = eventId, 
       CreatedDate = DateTime.Now.Date 
      }; 

      //Save mediaItem 
      _repo.SaveMediaItem(mediaItem); 

      return Request.CreateResponse(HttpStatusCode.Created); 
     } 
     else 
     { 
      return Request.CreateResponse(HttpStatusCode.BadRequest); 
     }   
    } 

http://localhost:24727/api/mediaitems/12341254234/1 

是这样的URL,然后我附上.JPG邮递员身上。 当我运行api请求时,它从来没有该文件,因此它永远不能保存。

+0

你可以尝试用一个小文件(用一串字符的文本文件),并使用Chrome开发者工具或小提琴手看到并复制到这里了请求正文。 –

+0

你调试过代码吗?是否调用MediaItems? 'upload.C​​ontentLength> 0'的哪个分支被执行? –

+0

我得到一个空引用异常上传,当我添加if(upload!= null && upload.C​​ontentLength> 0)if(upload.C​​ontentLength> 0)它只是跳过并返回一个错误的请求,这意味着没有HttpPostedFileBase – Sl1ver

回答

0

你可以像这样开始:我

[Route("~/api/mediaitems/{token}/{eventId}")] 
public async Task<HttpResponseMessage> MediaItems(string token, int eventId) 
{ 
    byte[] data = await this.Request.Content.ReadAsByteArrayAsync(); 

    //data will contain the file content, you can save it here 

    return Request.CreateResponse(HttpStatusCode.Created); 
} 

注意如何去除HttpPostedFileBase upload参数。

如果需要,您可以根据this.Request.Content进行一些验证。例如,你可能想检查内容的长度。

+0

如果我以这种方式执行操作,我确实收到了数据,但是如何将它保存到具有文件名的文件夹? – Sl1ver

0

也许帮助这个...添加到如下web.config中。您必须设置最大接受文件的字节大小:15728640 = 15MB

<configuration>  
    <location path="Custommer/edit"> 
    <system.web> 
     <httpRuntime maxRequestLength="15728640"/> 
    </system.web> 
    </location> 
</configuration>