2017-09-13 74 views
0

剃刀的WebAPI上傳文件我想利用這裏提供的答案: Upload File Using WebAPI AjaxC#與AJAX 400錯誤

,但我不斷收到400 (Bad Request)錯誤。

我已經提交PDF文件,但我不斷收到這個錯誤...

我在做什麼錯? (僅供參考我不使用MVC

我的代碼:

CSHTML(使用剃刀語法)

@{ 
    Layout = "~/_SiteLayout.cshtml"; 
} 

    <label>Enter File</label> 
    <input type="file" name="UploadFile" id="datasheet_uploadfile" class="" accept="application/pdf"/> 


<script> 
$(document).ready(function() { 
    $('#datasheet_uploadfile').change(function() {   
     var data = new FormData(); 
     var file = this.files; 

     data.append('file', file); 


     $.ajax({ 
      url: '/api/file', 
      processData: false, 
      contentType: false, 
      data: data, 
      type: 'POST' 
     }).done(function(result) { 
      alert(result); 
     }).fail(function(a, b, c) { 
      console.log(a, b, c); 
     }); 

    }); 

}); 
</script> 

我的WebAPI控制器

FileController。 cs

public class FileController : ApiController 
{ 

    // POST api/<controller> 
    public HttpResponseMessage Post() 
    { 
     HttpResponseMessage result = null; 
     var httpRequest = HttpContext.Current.Request; 
     if (httpRequest.Files.Count > 0) 
     { 
      var docfiles = new List<string>(); 
      foreach (string file in httpRequest.Files) 
      { 
       var postedFile = httpRequest.Files[file]; 
       int hasheddate = DateTime.Now.GetHashCode(); 
       //Good to use an updated name always, since many can use the same file name to upload. 
       string changed_name = hasheddate.ToString() + "_" + postedFile.FileName; 

       var filePath = HttpContext.Current.Server.MapPath("~/Content/stuff/" + changed_name); 
       postedFile.SaveAs(filePath); // save the file to a folder "Images" in the root of your app 

       changed_name = @"~\Content\stuff\" + changed_name; //store this complete path to database 
       docfiles.Add(changed_name); 

      } 
      result = Request.CreateResponse(HttpStatusCode.Created, docfiles); 
     } 
     else 
     { 
      result = Request.CreateResponse(HttpStatusCode.BadRequest); 
     } 

     return result; 
    } 

} 

回答

1

使用下面的代碼上傳文件

$(document).ready(function() { 
    $('#datasheet_uploadfile').change(function() { 
    var data = new FormData(); 
    data.append("file", this.files[0]);