I can upload file on my local machine successfully but when i try to upload on host it can't find the action. I don't know why. Here's my code.
HTML
<form method="post" asp-action="UploadFile" asp-controller="Admin" enctype="multipart/form-data">
<div class="custom-file">
<input type="file" class="custom-file-input" id="file" name="file">
<label class="custom-file-label" for="file">Browse</label>
</div>
<button class="btn btn-brand" type="submit">Upload</button>
</form>
C#
public IActionResult UploadFile([FromForm]IFormFile file)
{
var path = Path.Combine(_environment.WebRootPath, "uploads");
if (file!= null && file.Length > 0)
{
using (var reader = new FileStream(Path.Combine(path, "gallery", file.FileName), FileMode.Create))
{
file.CopyTo(reader);
}
Gallery gallery = new Gallery
{
Path = file.FileName
};
db.Gallery.Add(gallery);
db.SaveChanges();
}
return RedirectToAction("Gallery");
}
Related
I'm trying to use IBM Watson visual recognition in a web application. I want to send the path of the photo uploaded by the client to a function or a controller so I can use it to build and get a result from visual recognition(build an object).
I managed to get the path like this(in internet explorer):
var input = document.getElementById("file");
var filepath1 = input.value;
I want to know how can i send the path to a controller or to a function in c#.
I also tried to build a form and add an action to the controller but the controller name didn't show up.
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input accept="image/*" title="Choose an image to upload" type="file" name="file" id="file" />
<input type="submit" />
</form>
ViewModel
public class MyViewModel
{
[Display(Name = "My File")]
public IFormFile File { get; set; }
}
View
#model MyViewModel
<form asp-action="Send" enctype="multipart/form-data">
<label asp-for="File">Filename:</label>
<input accept="image/*" title="Choose an image to upload" type="file" asp-for="File" />
<input type="submit" />
</form>
Controller
[HttpPost]
public async Task<IActionResult> Send([Bind("File")] MyViewModel myVM)
{
if (myVM.File?.Length > 0)
{
byte[] fileBytes;
using (var fileStream = myVM.File.OpenReadStream())
using (var ms = new MemoryStream())
{
fileStream.CopyTo(ms);
fileBytes = ms.ToArray();
}
var fileName = Path.GetFileName(myVM.File.FileName);
var fileMimeType = myVM.File.ContentType;
var fileContent = fileBytes;
//You have all the file attributes and content
}
}
I'm trying to upload single .txt file, and read it's contents. I'm using IFormFile to do that. My controller is basically like
public IHttpActionResult PostCellInfo(IFormFile file)
{
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
}
}
and my form in index is
<form name="upload" method="post" enctype="multipart/form-data" action="api/CellInfoes">
<div>
<input name="file" type="file" />
<input type="submit" value="upload" />
</div>
</form>
But error still says
"ExceptionMessage":"Object reference not set to an instance of an
object."
I think "file" is always null. Any ideas why?
I've read that the names must match - but I think this is OK in my code.
The parameter should be IList<IFormFile> files.
public IHttpActionResult PostCellInfo(IList<IFormFile> files)
{
foreach (var file in files) {
if (file.Length > 0) {
using (var reader = new StreamReader(file.OpenReadStream()))
{
var fileContent = reader.ReadToEnd();
}
}
}
}
And change the name attribute in the view also:
<form name="upload" method="post" enctype="multipart/form-data" action="api/CellInfoes">
<div>
<input name="files" type="file" />
<input type="submit" value="upload" />
</div>
</form>
I haven't tested this but it should point you in the right direction.
If you want to use IFormFile without the collection you should check this post.
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
var _Img = new ImageBusiness();
var imge = new ImgView { FileName = file.FileName, FileType = file.ContentType };
imge.FileData = new byte[file.ContentLength];
file.InputStream.Read(imge.FileData, 0, file.ContentLength);
_Img.AddImge(imge);
ViewBag.Result = true;
return View ();
}
catch(Exception)
{
ModelState.AddModelError("","An error accured while uploading Image, please try again.");
return View();
}
}
this my view
#using (Html.BeginForm("Upload", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary();
<input name="file" /><br />
<input type="submit" class="btn btn-small" value="Save Brochure" />
}
theres no bugs just on run time when uploading of an image doesnt give me broswer option to select a picture.help will be appreciated thanks
hello i think maybe you missing type file on your input
try something like
<input type="file" name="file" /><br />
<input type="submit" class="btn btn-small" value="Save Brochure" />
I have just deployed my c# web application to windows azure. Image upload works fine on my local machine however now the website has been deployed the image upload doesn't work with azure storage. I just recieve an error saying Error. An error occurred while processing your request. When trying to upload an image.
Any help would be grateful.
Image Upload Controller
public ActionResult Create(UserprofileImage userprofileimage, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var currentUser = manager.FindById(User.Identity.GetUserId());
file.SaveAs(HttpContext.Server.MapPath("~/Images/")
+ file.FileName);
userprofileimage.userImagePath = file.FileName;
userprofileimage.UserId = currentUser.Id;
userprofileimage.current = 1;
db.UserprofileImages.Add(userprofileimage);
db.SaveChanges();
var userimage = db.UserprofileImages.Where(u => u.UserId == currentUser.Id && u.Id != userprofileimage.Id).ToList();
foreach(var item in userimage)
{
item.Id = 0;
db.SaveChanges();
}
return RedirectToAction("Index", "Profile");
}
}
return View(userprofileimage);
}
** Image Upload HTML **
#using (Html.BeginForm("Create", "UserprofileImage", null, FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
<div class="control-label col-md-2">
Profile Image
</div>
<div class="col-md-10">
<input id="userImagePath" title="Upload a profile picture"
type="file" name="file" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
As Aran suggested in the comments above, I too would recommend that you store your images in blob storage. Storing images on the hard drive should only be done for static images, which would be bundled and deployed with your solution. You cannot count on the images being present if you instance of your site is moved to another server. Storing images in SqlAzure tables or blobs will also enable you to better scale your application should you wish to increase the number of website instances you employ for you solution
Below is an example code snippet I use which gives you an idea of how to use the storage client to write to blob.
public async Task AddPhotoAsync(Photo photo)
{
var containerName = string.Format("profilepics-{0}", photo.ProfileId).ToLowerInvariant();
var blobStorage = _storageService.StorageAccount.CreateCloudBlobClient();
var cloudContainer = blobStorage.GetContainerReference("profilephotos");
if(cloudContainer.CreateIfNotExists())
{
var permissions = await cloudContainer.GetPermissionsAsync();
permissions.PublicAccess = BlobContainerPublicAccessType.Container;
cloudContainer.SetPermissions(permissions);
}
string uniqueBlobName = string.Format("profilephotos/image_{0}{1}", Guid.NewGuid().ToString(),Path.GetExtension(photo.UploadedImage.FileName));
var blob = cloudContainer.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = photo.UploadedImage.ContentType;
blob.UploadFromStream(photo.UploadedImage.InputStream);
photo.Url = blob.Uri.ToString();
await AddPhotoToDB(photo);
}
I want to upload image to the server, The below code is working properly when i run the the code locally on my system, but when i upload it to the server it gives error message - The model item passed into the dictionary is of type 'Login.Models.User', but this dictionary requires a model item of type 'System.Collection.Generic.IEnumerable'[Login.Models.User]'.Please help to solve this issue.
public ActionResult FileUpload(HttpPostedFileBase file, Login.Models.User model)
{
if(ModelState.IsValid)
{
try
{
var user=db.User.FirstOrDefault(c=>c.Userid==model.Userid);
if (file != null)
{
string pic = System.IO.Path.GetFileName(file.FileName);
string path = System.IO.Path.Combine(Server.MapPath("~/images/profile/"), pic);
file.SaveAs(path);
user.imagepath = "http://sampleApp.com/images/profile/" + pic;
}
Catch(Exception ex)
{
ModelState.AddModelError("",ex.Message);
}
return View("ViewAdmin",model);
}
db.ObjectStateManager.ChangeObjectState(user,System.Data.EntityState.Modified);
db.SaveChanges();
return RedirectToAction("User");
}
View
#model Login.Models.User
#using (Html.BeginForm("FileUpload", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
{
<label for="file">Upload Image:</label>
<input type="file" name="file" id="file" style="width: 100%;" />
<input type="submit" value="Upload" class="submit" />
}