Reputation: 1343
I am having an issue on the controller side using ASP.Net MVC 3 trying to upload an image to amazon s3. Here is what I have and the error.
Here is my HTML form.
@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>
}
And here is the code in my controller
[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");
}
The error I am getting is.
Server Error in '/' Application.
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
Line 28: if (file.ContentLength > 0)
Upvotes: 3
Views: 3243
Reputation: 87037
@using (Html.BeginForm("Index", "YourController", FormMethod.Post, new { enctype = "multipart/form-data" }))
and change
if (file.ContentLength > 0)
to
if (file == null || file.ContentLength <= 0)
{
// Add some client side error message.
// Return the view
return View();
}
// Upload...
var request = new PutObjectRequest();
...
Upvotes: 1
Reputation: 4262
Does this help?
using (@Html.BeginForm(new { enctype = "multipart/form-data" }))
You've Been Haacked - Uploading Files
Upvotes: 4
Reputation: 218862
Use break points and debug the code. See whether your objects are null or not. Accessing a property / method of a null object will give you this error usually.
Upvotes: 1