2011-12-12 75 views
3

我在使用ASP.Net MVC 3嘗試將圖像上傳到amazon s3的控制器端存在問題。這是我所擁有的和錯誤。使用ASP.Net MVC將圖像上傳到Amazon S3 3

這是我的HTML表單。

@using (Html.BeginForm()) 
{ 
    <div class="in forms"> 

     <input type="file" id="file" name="file" class="box" /></p> 

     <p><input type="submit" value="Upload" id="btnSubmit" class="com_btn" /></p> 

} 

這裏是代碼,在我的控制器

[HttpPost] 
    public ActionResult Index(HttpPostedFileBase file) 
    { 
     AmazonS3 client = Amazon.AWSClientFactory.CreateAmazonS3Client("*redacted*","*redacted*"); 
     if (file.ContentLength > 0) 
     { 
      var request = new PutObjectRequest(); 
      request.WithBucketName("*redacted*"); 
      request.WithKey(file.FileName); 
      request.FilePath = Path.GetFullPath(file.FileName); 
      request.ContentType = file.ContentType; 
      request.StorageClass = S3StorageClass.ReducedRedundancy; 
      request.CannedACL = S3CannedACL.PublicRead; 
      client.PutObject(request); 
      return Redirect("UploadSuccess"); 
     } 
     return RedirectToAction("Index"); 
    } 

我得到的錯誤是。

'/'應用程序中的服務器錯誤。

未將對象引用設置爲對象的實例。

描述:執行當前Web請求期間發生未處理的異常。請查看堆棧跟蹤以獲取有關該錯誤的更多信息以及源代碼的位置。

異常詳細信息:System.NullReferenceException:未將對象引用設置爲對象的實例。

源錯誤:

線28:如果(file.ContentLength> 0)

回答

4

這有幫助嗎?

using (@Html.BeginForm(new { enctype = "multipart/form-data" })) 

You've Been Haacked - Uploading Files

+0

這並沒有改變什麼不幸 –

+1

改變它爲:@using(Html.BeginForm(「Index」,「YourController」,FormMethod.Post,new {enctype =「multipart/form-data」}))' – hawkke

+0

@using(Html.BeginForm(「Index」,「YourController」,FormMethod.Post,new {enctype =「multipart/form-data」}))< - This Fixed It –

1

使用斷點和調試代碼。看看你的對象是否爲空。訪問空對象的屬性/方法通常會給你這個錯誤。

+0

我已經這樣做了HttpPostedFileBase文件快到了爲空出於某種原因,即使我傳遞fi的輸入類型來自chtml頁面。 –

1
@using (Html.BeginForm("Index", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" })) 

,改變

if (file.ContentLength > 0) 

if (file == null || file.ContentLength <= 0) 
{ 
    // Add some client side error message. 

    // Return the view 
    return View(); 
} 

// Upload... 
var request = new PutObjectRequest(); 
... 
相關問題