2016-07-09 213 views
1

我在web api.I的項目中工作,在圖片上有一些問題到api/App_Data文件夾。如何在web api上上傳圖片

我的看法代碼如下

<form data-bind="submit: uploadApi"> 
     <div> 
      <label for="caption">Image Caption</label> 

     </div> 
     <div> 
      <label for="image1" >Image File</label> 
      <input name="image1" type="file" data-bind="value: imgPath" /> 
     </div> 
     <div> 
      <input type="submit" value="Submit" /> 
     </div> 
    </form> 
</div> 

我的jQuery代碼如下所示

self.uploadApi = function() { 
    /* var data = { 
     imgpath: self.imgPath() 
    }; 
    alert(self.imgPath());*/ 



    var data = new FormData(); 
    var file = self.imgPath(); 
    data.append('file', file); 

    $.ajax({ 
     type: 'POST', 
     url: '/api/Upload', 
     processData: false, 
     // contentType: 'application/json; charset=utf-8', 
     // data: JSON.stringify(data) 
     contentType: false, 
     data:data 
    }).done(function (data) { 
     self.result("Done!"); 
    }).fail(showError); 



} 

控制器是如下

public async Task<string> PostFormData() 
    { 





     var provider = new MultipartMemoryStreamProvider(); 
     await Request.Content.ReadAsMultipartAsync(provider); 

     // extract file name and file contents 
     var fileNameParam = provider.Contents[0].Headers.ContentDisposition.Parameters.FirstOrDefault(p => p.Name.ToLower() == "filename"); 
     string fileName = (fileNameParam == null) ? "" : fileNameParam.Value.Trim('"'); 
     byte[] file = await provider.Contents[0].ReadAsByteArrayAsync(); 

     // Here you can use EF with an entity with a byte[] property, or 
     // an stored procedure with a varbinary parameter to insert the 
     // data into the DB 

     var result = string.Format("Received '{0}' with length: {1}", fileName, file.Length); 
     return result; 










    } 

,但我不能夠上傳e image

回答

0

您正在以錯誤的方式創建FormData。其中一個選項是:

var form = $('form')[0]; 
var formData = new FormData(form); //it will already include the selected file