2015-11-05 78 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>