2011-12-12 80 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(); 
... 
相关问题