I'am trying create some validation for file size. My code:
[HttpPost]
public ActionResult Index(FotoModel model)
{
TryUpdateModel(model);
if (ModelState.IsValid)
{
if (model != null && model.File != null)
{
var fileName = Path.GetFileName(model.File.FileName);
var fileExtension = Path.GetExtension(fileName);
long fileSize = new FileInfo(fileName).Length;
fileName = "file" + fileExtension;
var path = Path.Combine(Server.MapPath("~/Content/Images"), fileName);
if (fileSize < 55000)
{
model.File.SaveAs(path);
model.link = fileName.ToString();
}
else
{
ViewData["Size"] = "Akceptowane pliki: jpg, jpeg, png o maksymalnym rozmiarze 50 KB";
}
return View(model);
}
}
return View(model);
}
And in this line:
long fileSize = new FileInfo(fileName).Length;
I'am receiving error: "File cannot be found". Do You know how can I resolved this ?
In Asp.Net MVC we have to use HttpPostedFileBase for Uploaded files as shown below :-
public ActionResult Index(FotoModel model, HttpPostedFileBase file)
{
if (file != null)
{
int byteCount = file.ContentLength; // <---Your file Size or Length
.............
.............
}
}
What you are looking is a ContentLength
public ActionResult Index(FotoModel model)
{
if (model != null && model.File != null)
{
var fileSize = model.File.ContentLength;
}
}
Related
[HttpPost]
public async Task<IActionResult> UploadImage(ImageViewModel imageviewmodel, IFormFile Image)
{
var user = new AdminController(_context).GetUserId(Request);
if (user != null)
{
imageViewModel.Id = user.Id;
string name = $"{DateTime.UtcNow.Ticks}-";
if (Image == null || Image.Length == 0)
return Content("File not found");
var path = Path.Combine(
Directory.GetCurrentDirectory(), "wwwroot/Images", Image.FileName);
using (var stream = new FileStream(path, FileMode.Create))
{
await Image.CopyToAsync(stream);
string content_type = Image.ContentType;
}
imageviewmodel.Image = name + Image.FileName;
_context.ImageViewModels.Update(imageviewmodel);
await _context.SaveChangesAsync();
return RedirectToAction("Index");
}
else
{
return Redirect("/Account/Login");
}
}
asp.net core MVC - framework net6.0
I have a page in which i upload an image and save it to the db.
the file i'm getting from the view is IFormFile.
I want to be able to check the resolution (width and height) of the photo before saving in DB.
Can it be done with IFormFile?
here is the controller that handles the file :
public JsonResult Submit(IFormFile PhotoFile)
{
int success = 0;
string excep = "";
try
{
if (PhotoFile.Length > 0)
{
using (var ms = new MemoryStream())
{
PhotoFile.CopyTo(ms);
var fileBytes = ms.ToArray();
}
}
ApplicationUser appUser =
_unitOfWork.ApplicationUser.GetAll().Where(a => a.UserName == User.Identity.Name).FirstOrDefault();
if (appUser != null)
{
FileUpload fileUpload = new FileUpload()
{
file = PhotoFile,
CompanyId = appUser.CompanyId
};
SaveFile(fileUpload);
}
excep = "success";
success = 1;
return Json(new { excep, success });
}
catch (Exception ex)
{
excep = "fail";
success = 0;
return Json(new { excep, success });
}
}
public string SaveFile(FileUpload fileObj)
{
Company company = _unitOfWork.Company.GetAll().
Where(a => a.Id == fileObj.CompanyId).FirstOrDefault();
if(company != null && fileObj.file.Length > 0)
{
using (var ms = new MemoryStream())
{
fileObj.file.CopyTo(ms);
var fileBytes = ms.ToArray();
company.PhotoAd = fileBytes;
_unitOfWork.Company.Update(company);
_unitOfWork.Save();
return "Saved";
}
}
return "Failed";
}
As far as I know this isn't possible with just IFormFile and you need System.Drawing.Common.
So first you need to convert it like:
using var image = Image.FromStream(PhotoFile.OpenReadStream());
Then you can simply get the height/width with image.height and image.width
I, am using angular 5, with asp.net core 2.0. I, am trying to upload the file to the server. The code update the file to the server. But with 0 kb of data and sometime it upload the file.
The file size is not large. Its in KB.
Here is the Angular code
public QuestionPostHttpCall(_questionPhotoVM: QuestionPhotoViewModel): Observable<GenericResponseObject<QuestionPhotoViewModel[]>> {
const formData: FormData = new FormData();
formData.append('FileUpload', _questionPhotoVM.FileUpload);
formData.append('QuestionText', _questionPhotoVM.questionText);
formData.append('QuestionId', _questionPhotoVM.questionId);
const headers = new HttpHeaders().set('enctype', 'multipart/form-data');
return this._httpClientModule.post<GenericResponseObject<QuestionPhotoViewModel[]>>(this.questionPhotoUrl, formData);
}
In the controller I, can receive the file.
Here is the controller method
[HttpPost]
public JsonResult QuestionPhotoPost(IFormFile FileUpload, string QuestionText, Guid? QuestionId)
{
string TempFileName = string.Empty;
var directiveToUpload = Path.Combine(_environment.WebRootPath, "images\\UploadFile");
var http = HttpRequestExtensions.GetUri(Request);
QuestionViewModel model = new QuestionViewModel();
try
{
if (FileUpload != null)
{
TempFileName = FileUpload.FileName;
CheckFileFromFrontEnd();
}
}
catch (Exception exception)
{
}
void CheckFileFromFrontEnd()
{
if (FileUpload != null)
{
if (!System.IO.Directory.Exists(directiveToUpload))
{
System.IO.Directory.CreateDirectory(directiveToUpload);
}
if (System.IO.File.Exists(string.Format("{0}\\{1}\\{2}", _environment.WebRootPath, "images\\UploadFile", FileUpload.FileName)))
{
TempFileName = Guid.NewGuid().ToString() + FileUpload.FileName;
}
model.PictureUrl = string.Format("{0}://{1}/{2}/{3}/{4}", http.Scheme, http.Authority, "images", "UploadFile", TempFileName);
SaveFileToServer(TempFileName);
}
}
void SaveFileToServer(string FileName)
{
if (FileUpload.Length > 0)
{
using (var stream = new FileStream(Path.Combine(directiveToUpload, FileName), FileMode.Create))
{
FileUpload.CopyToAsync(stream);
}
}
}
return Json(genericResponseObject);
}
The file is uploaded to the server. But some time it upload with 0 byte and sometime it upload correctly.
The resolution of file is 570 X 400 and size of file 197KB
Where I, am doing wrong?? Please anyone let me know. Do, I need to specify max byte in somewhere ??
Your problem is that you are using an asynchronous function and not awaiting it.
You are using ASP.NET Core so you should (read "must") use the async-all-the-way pattern:
[HttpPost]
public async Task<JsonResult> QuestionPhotoPost(IFormFile FileUpload, string QuestionText, Guid? QuestionId)
{
string TempFileName = string.Empty;
var directiveToUpload = Path.Combine(_environment.WebRootPath, "images\\UploadFile");
var http = HttpRequestExtensions.GetUri(Request);
QuestionViewModel model = new QuestionViewModel();
try
{
if (FileUpload != null)
{
TempFileName = FileUpload.FileName;
await CheckFileFromFrontEndAsync();
}
}
catch (Exception exception)
{
}
async Task CheckFileFromFrontEndsync()
{
if (FileUpload != null)
{
if (!System.IO.Directory.Exists(directiveToUpload))
{
System.IO.Directory.CreateDirectory(directiveToUpload);
}
if (System.IO.File.Exists(string.Format("{0}\\{1}\\{2}", _environment.WebRootPath, "images\\UploadFile", FileUpload.FileName)))
{
TempFileName = Guid.NewGuid().ToString() + FileUpload.FileName;
}
model.PictureUrl = string.Format("{0}://{1}/{2}/{3}/{4}", http.Scheme, http.Authority, "images", "UploadFile", TempFileName);
await SaveFileToServerAsync(TempFileName);
}
}
async Task SaveFileToServerAsync(string FileName)
{
if (FileUpload.Length > 0)
{
using (var stream = new FileStream(Path.Combine(directiveToUpload, FileName), FileMode.Create))
{
await FileUpload.CopyToAsync(stream);
}
}
}
return Json(genericResponseObject);
}
To make the code more readable, I'd move those inline functions to outside, though.
I want to get the path of the image from where it is being uploaded...
Ex:my image is in E:drive and in images folder and i want to get that path before i upload the image
My Controllercode is below
public ActionResult UploadImage(UploadImageModel model)
{
if (ModelState.IsValid)
{
Bitmap original = null;
var name = "newimagefile";
var errorField = string.Empty;
if (model.IsUrl)
{
errorField = "Url";
name = GetUrlFileName(model.Url);
original = GetImageFromUrl(model.Url);
}
else if (model.IsFlickr)
{
errorField = "Flickr";
name = GetUrlFileName(model.Flickr);
original = GetImageFromUrl(model.Flickr);
}
else if (model.File != null)
{
errorField = "File";
name = Path.GetFileNameWithoutExtension(model.File.FileName);
original = Bitmap.FromStream(model.File.InputStream) as Bitmap;
}
if (original != null)
{
var img = CreateImage(original, model.X, model.Y, model.Width, model.Height);
var fn = Server.MapPath("~/Content/img/" + name + ".png");
img.Save(fn, System.Drawing.Imaging.ImageFormat.Png);
return RedirectToAction("Index");
}
else
ModelState.AddModelError(errorField, "Your upload did not seem valid. Please try again using only correct images!");
}
return View(model);
}
it is not possible . it is a security threat if the browser sends the full path from client side.
I am trying to upload several db images onto the SQL Server 2008R2. I am using ASP.NET MVC 3 in C#. What is happening is that I getting the images displayed but the problem is that the second image is being displayed as twice. So it is duplicate. I am not sure why the first image is not being displayed.
My SubProductCategory4 Table has the following columns (for simplicity sake)...
Column Names: Image1 and Image2 has DataTypes varbinary(MAX), another column Name: ImageMimeType has DataTypes varchar(50).
My Controller has the following code for Create method...
[HttpPost]
public ActionResult Create([Bind(Exclude = "SubProductCategoryFourID")] SubProductCategory4 Createsubcat4, IEnumerable<HttpPostedFileBase> files, FormCollection collection)
{
if (ModelState.IsValid)
{
foreach (string inputTagName in Request.Files)
{
if (Request.Files.Count > 0) // tried Files.Count > 1 did
// not solve the problem
{
Createsubcat4.Image1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
Createsubcat4.Image2 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
// var fileName = Path.GetFileName(inputTagName);
//var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
}
// moved db.AddToSubProductCategory4(Createsubcat4);
// here but did not solve the problem
}
db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
return RedirectToAction("/");
}
//someother code
return View(Createsubcat4);
}
GetImage method...
public FileResult GetImage(int id)
{
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
MemoryStream streaml;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if ((z != null && z.Image1 != null) && (z != null && z.Image2 != null))
{
stream = new MemoryStream(z.Image1);
streaml = new MemoryStream(z.Image2);
}
else
{
var path = Server.MapPath(alternativePicturePath);
foreach (byte item in Request.Files)
{
HttpPostedFileBase file = Request.Files[item];
if (file.ContentLength == 0)
{
continue;
}
}
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
/* streaml = new MemoryStream();
var imagey = new System.Drawing.Bitmap(path);
imagey.Save(streaml, System.Drawing.Imaging.ImageFormat.Jpeg);
streaml.Seek(0, SeekOrigin.Begin);*/
}
return new FileStreamResult(stream,"image/jpg");
}
FileHandler.cs
public class FileHandler
{
public byte[] uploadedFileToByteArray(HttpPostedFileBase file)
{
int nFileLen = file.ContentLength;
byte[] result = new byte[nFileLen];
file.InputStream.Read(result, 0, nFileLen);
return result;
}
}
create.cshtml...
#using (Html.BeginForm("Create", "ProductCategoryL4", "GetImage",
FormMethod.Post, new { enctype = "multipart/form-data" }))
//some code then...
<div class="editor-field">
#Html.EditorFor(model => model.Image1)
<input type="file" id="fileUpload1" name="fileUpload1" size="23"/>
#Html.ValidationMessageFor(model => model.Image1)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Image2)
<input type="file" id="fileUpload2" name="fileUpload2" size="23"/>
#Html.ValidationMessageFor(model => model.Image2)
</div>
index.cshtml...
<img src="#Url.Action("GetImage", "ProductCategoryL4", new { id =
item.SubProductCategoryFourID })" alt="" height="100" width="100" />
</td>
<td>
<img src="#Url.Action("GetImage", "ProductCategoryL4", new { id =
item.SubProductCategoryFourID })" alt="" height="100" width="100" />
</td>
I am using using VS2010, ASP.NET MVC3 in C# with SQL Server 2008R2. Thanks in advance but please only respond if you know the answer. If there is a better way of doing this please let me know.
The code that is listed is looping through the files, and for each one, setting both Image1 and Image2 to be the same thing. When you upload 2 files, they are both showing up as image 2 because that was the last image applied to both fields.
Try replacing the loop with something more like this, which sets the fields one at a time if there are enough images.
FileHandler fh = new FileHandler();
if (Request.Files.Count > 0)
{
Createsubcat4.Image1 = fh.uploadedFileToByteArray(Request.Files[0]);
}
if (Request.Files.Count > 1)
{
Createsubcat4.Image2 = fh.uploadedFileToByteArray(Request.Files[1]);
}
db.AddToSubProductCategory4(Createsubcat4);
If you need to open this up to allow more images in the future, you'll want to replace the Image1 and Image2 fields with a collection of images, and use your loop again to add each image in the uploaded files collection. Something like this:
FileHandler fh = new FileHandler();
foreach (HttpPostedFileBase uploadedImage in Request.Files)
{
Createsubcat4.Images.Add(fh.uploadedFileToByteArray(uploadedImage));
}
db.AddToSubProductCategory4(Createsubcat4);
db.SaveChanges();
EDIT:
Now that you are saving the images correctly, you need to take a second look at your GetImage action. You'll notice that you correctly load both files into memory, however when you specify your action result (return new FileStreamResult(stream,"image/jpg");) you are only ever returning the first stream. You need a way to return the second stream when requested. There are a couple ways to go about this, add another input parameter to specify which image to load or create a second action that only returns the second one.
To create the two action set up, your code would look something like this:
public ActionResult GetImage1(int id)
{
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if (z != null && z.Image1 != null)
{
stream = new MemoryStream(z.Image1);
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
public ActionResult GetImage2(int id)
{
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
if (z != null && z.Image2 != null) // the difference is here
{
stream = new MemoryStream(z.Image2); // the difference is also here
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
These functions are almost identical and can easily be made 1 which takes a parameter to select which image to load.
public ActionResult GetImage(int id, int? imageNum)
{
imageNum = imageNum ?? 0;
const string alternativePicturePath = #"/Content/question_mark.jpg";
MemoryStream stream;
SubProductCategory4 z = db.SubProductCategory4.Where(k => k.SubProductCategoryFourID == id).FirstOrDefault();
byte[] imageData = null;
if (z != null)
{
imageData = imageNum == 1 ? z.Image1 : imageNum == 2 ? z.Image2 : null;
}
if (imageData != null)
{
stream = new MemoryStream(imageData);
}
else
{
var path = Server.MapPath(alternativePicturePath);
stream = new MemoryStream();
var imagex = new System.Drawing.Bitmap(path);
imagex.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Seek(0, SeekOrigin.Begin);
}
return new FileStreamResult(stream,"image/jpg");
}
This function would specify the imageNum as a query parameter like:
http://www.mydomain.com/controllerName/GetImage/{id}?imageNum={imageNum}
I think your problem might be in this loop.
foreach (string inputTagName in Request.Files)
{
if (Request.Files.Count > 0)
{
Createsubcat4.Image1 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
Createsubcat4.Image2 = (new FileHandler()).uploadedFileToByteArray((HttpPostedFileBase)Request.Files[inputTagName]);
// var fileName = Path.GetFileName(inputTagName);
//var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
}
}
db.AddToSubProductCategory4(Createsubcat4);
The Request.Files.Count > 0 should always be true since you are iterating through a list of Files. However, the real issue is that with this loop you overwrite the properties of Createsubcat4 with each file, and then after the properties are set with the last file, that is what gets sent to the database.
If you are trying to add multiple records into the database (one for each image), you'll need to move the AddToSubProductCategory4 within the loop. If you are trying to add two images to just that record, I'd recommend assigning each by name, and skipping the foreach loop.
public JsonResult Update(ProductViewModel model, HttpPostedFileBase imgpath1, IEnumerable<HttpPostedFileBase> imgpath2)
{
if (imgpath1 != null)
{
foreach (HttpPostedFileBase postedFile in imgpath1)
{
// var prodimage = Request.Files[i];
}
}
if (imgpath2 != null)
{
foreach (HttpPostedFileBase postedFile in imgpath2)
{
var prodimage = Request.Files[i];
}
}
}