simple image upload in aspnet mvc - asp.net-mvc

i'm building a simple school portal, i have stucked at uploading an image into my application, i.e a user should upload school image to my server, i have directory for images as ./Content/Images -- all uploading images should be uploaded to this directory. i have following code
input type="file" id="SchoolImageUrl" name="SchoolImageUrl" class="required"
using this m'getting a browse button, i have no idea how to upload that image to server and how would be my action controller ? i have following controller for creating school
public ActionResult SchoolCreate(_ASI_School schoolToCreate, FormCollection collection)
{
if (!ModelState.IsValid)
return View();
try
{
// TODO: Add insert logic here
schoolToCreate.SchoolId = Guid.NewGuid().ToString();
schoolToCreate.UserId = new Guid(Request.Form["currentUser"]);
schoolToCreate.SchoolAddedBy = User.Identity.Name;
HttpPostedFileBase file = Request.Files["SchoolImageUrl"];
file.SaveAs(file.FileName);
//schoolToCreate.SchoolImageUrl = Reuseable.ImageUpload(Request.Files["SchoolImageUrl"], Server.MapPath("../Content"));
//schoolToCreate.SchoolImageUrl = Path.GetFullPath(Request.Files[0].FileName);
schoolToCreate.SchoolImageUrl = collection["SchoolImageUrl"];
UpdateModel(schoolToCreate);
_schoolRepository.CreateSchool(schoolToCreate);
//_schoolRepository.SaveToDb();
return RedirectToAction("DepartmentCreate", "Department", new { userId = schoolToCreate.UserId, schoolId = schoolToCreate.SchoolId });
}
catch
{
return View("CreationFailed");
}
}
here im geting object referece error

Does your Html.BeginForm include this:
new { enctype = "multipart/form-data" }
Otherwise the file data won't be sent in the POST request.

Take a look at this post
HttpPostedFileBase file = Request.Files["SchoolImageUrl"];
may be causing it. Did you debug to check if it's getting a null value?

Related

How to get creation or modified date of uploaded files(From local pc)

I want to get last modified date of uploaded files without creating path on server.
Basically
#using (Html.BeginForm("UploadFiles", "QuestionForm", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="files" multiple="multiple" id="Button_select" />
}
Controller
[HttpPost("UploadFiles")]
public async Task<IActionResult> UploadFiles([Bind] QuestionModel modelVal)
{
var httpRequest = Request.Form;
foreach (IFormFile uploadedFile in httpRequest.Files)
{
//Saving to database
}
}
After upload I'm saving files in database instead of server.
How can I know uploaded files last modified date or creation date.
Edited= I'm uploading files from my local storage.
I want to get last modified date of uploaded files without creating
path on server.
Well, we can get the file details information when it has written last time or modified using GetLastWriteTime() or GetCreationTime() method.
Implementation:
Let's assume I have below files in my application:
Now, I would like to search TestImage.jpg when it was modified last time. As we can see it was modifid on 1-Jun-22:9.20am. So let's implement on controller code snippet:
public async Task<ActionResult> GetFileInformation()
{
var fileName = "TestImage.jpg";
var path = Path.Combine(_environment.WebRootPath, "ImageName/Cover", fileName);
var lastModified = System.IO.File.GetLastWriteTime(path);
return Ok();
}
Note: Point that, here "ImageName/Cover" is refering the folder name where you would like to execute your search operation.
In addition, please check implementation details for more method based on your requirement:
Output:
Alternative Way:
System.IO.FileInfo fi = null;
fi = new FileInfo(fileName);// Here pass the file you want to search
var createdTime = fi.CreationTime;
var lastAccessTime = fi.CreationTime;
var lastWriteTime = fi.LastWriteTime;
Note: For more details you could have a look on our official document here.

data entered in fields disappears when file is uploaded

I have this form with a lot of input fields in page including dropdownlist, textboxes and textarea. And at the end of page, I have file uploading field.
The problem is when I entered all the data in the fields and I attached a file at the end, all the data I entered disappears and I need to retype again.
I have this code below. Here I use a Session to hold the data to retain the values entered in fields when uploading a file, but still the data disappears after a file has uploaded.
Can someone help me resolve this? Thank you so much.
CONTROLLER
[HttpGet]
[Authorize]
public ActionResult Create()
{
All_Issues all_Issues = new All_Issues();
ViewBag.StatusID = new SelectList(db.issue_status_ref, "StatusID", "StatusName");
ViewBag.IncLevelID = new SelectList(db.incident_level_ref, "IncLevelID", "Description");
ViewBag.DeptID = new SelectList(db.all_department_ref, "department_id", "department_name");
ViewBag.CatID = new SelectList(db.category_ref, "CatID", "Category");
ViewBag.NocID = new SelectList(db.nature_of_occurrence_ref, "NocID", "Title");
ViewBag.UsersID = new SelectList(db.ad_users, "user_id", "display_name");
if (Session["ir_session"] != null)
{
return View("Create", (All_Issues)Session["ir_session"]);
}
return View(new All_Issues());
}
FILE UPLOAD
[HttpPost]
public ActionResult FileUpload(Guid? IRID, All_Issues all_Issues)
{
Session["ir_session"] = all_Issues;
HttpFileCollectionBase ir_files;
List<files_ref> ir_uploadFileModel = new List<files_ref>();
ir_files = Request.Files;
string mapPath = "~/App_Data/UploadedFiles/";
FileUploads ir_fileupload = new FileUploads();
ir_fileupload.UploadFiles(null, null, IRID, ir_files, mapPath, "IR");
if (IRID == null)
{
return RedirectToAction("Create");
}
else
{
return RedirectToAction("Edit", new { id = IRID });
}
}
Already found a solution to this. Just took a long time to post an update.
What I did is still the same. I use session to store the data in my fields and I call this session in every action so that whenever I made a lot of action in the form, the data will retain until the page is submitted.
if (Session["ir_session"] != null)
{
IMRDTO model = (IMRDTO)Session["ir_session"];
return View("Create", (IMRDTO)Session["ir_session"]);
}
And with this line of code, which I call in every action, I retain all the data in fields even when the page reloaded.
Session["ir_session"] = imr;
Hoping it would also help someone.

Uploading file from iOS to MVC controller

I have a very simple file upload method on my MVC controller which works very well when uploading images from the browsers on my PC.
Uploading Code :
[HttpPost]
public ActionResult FileUpload(HttpPostedFileBase file, string encodedId)
However, if I try to upload an image from my iPhone I get error as
No route in the route table matches the supplied values
I tried removing the parameters from the method and instead accessing the data from the Request object:
Modified Code :
[HttpPost]
public ActionResult FileUpload()
{
var file = HttpContext.Request.Files[0];
string encodedId = HttpContext.Request.Form["EncodedId"];
This results in the same error.
I cant't ascertain what the iPhone is sending to the server as I don't have any kind of development tools on my iPhone.
I name my File which i am sending as File and get it via following code.
[HttpPost]
[Route("UploadAttachment")]
public IHttpActionResult UploadAttachment()
{
try
{
HttpPostedFile File = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files.Get("File") : null;
if (File != null)
{
Uploader uploader = new Uploader();
var Result = uploader.uploadToServer(File);
return Ok(Result);
}
else
{
return BadRequest("File is Required");
}
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}

View not updating after post with ASP.Net MVC

I'm trying to build a very simple website to display some test data being added & updated using asp.net mvc (with razor) but whenever data is posted to my Post method, my data is not being updated. I'm trying to get a unordered list (for now) to be updated the second a post is triggered.
I'm posting my data as JSON using the following code:
string jsonDeviceData = SerializeHelper.Serialize<IDeviceData>(deviceData,
ContentTypeEnum.Json, false);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(localServerUrl);
webRequest.Method = "POST";
webRequest.ContentType = "application/json"; //"application/x-www-form-urlencoded";
byte[] deviceDataBuffer = Encoding.UTF8.GetBytes(jsonDeviceData);
Task<Stream> requestTask = webRequest.GetRequestStreamAsync();
using (Stream requestStream = requestTask.Result)
{
requestStream.Write(deviceDataBuffer, 0, deviceDataBuffer.Length);
}
Task<WebResponse> responseTask = webRequest.GetResponseAsync();
using (StreamReader requestReader = new StreamReader(responseTask.Result
.GetResponseStream()))
{
string webResponse = requestReader.ReadToEnd();
Debug.WriteLine("Web Response: " + webResponse);
}
Below is the code I'm using in the POST method. Don't worry about the logic being so simplistic and probably horrible, but I'm just dabbling with this idea. Data will be stored in SQL Server database and I'll use EF if I decide to go further with this:
[HttpPost()]
public ActionResult Index(DeviceModel model)
{
if (ModelState.IsValid && model != null)
{
var deviceViewModelList = HttpContext.Application["DeviceList"]
as List<DeviceViewModel> ?? new List<DeviceViewModel>();
if (deviceViewModelList.All(m => !string.Equals(m.Name,
model.Name,
StringComparison.InvariantCultureIgnoreCase)))
{
deviceViewModelList.Add(new DeviceViewModel(model));
}
HttpContext.Application["DeviceList"] = deviceViewModelList;
var homePageViewModel = new HomePageViewModel
{
DeviceList = deviceViewModelList
};
return RedirectToAction("Index");
}
else
{
return View();
}
}
My model is passed correctly and everything works ok when the data is posted my page is not updated, even after calling RedirectToAction("Index");
The code below gets called the first time the page is loaded and after calling the RedirectToActio("Index"):
public ActionResult Index()
{
ViewBag.Title = "Test Server";
var deviceViewModelList = HttpContext.Application["DeviceList"]
as List<DeviceViewModel> ?? new List<DeviceViewModel>();
var homePageViewModel = new HomePageViewModel
{
DeviceList = deviceViewModelList
};
return View(homePageViewModel);
}
This is the code I have in my .cshtml page:
<ul>
#if (Model?.DeviceList != null)
{
foreach (var device in Model.DeviceList)
{
<li>#device.Name</li>
}
}
</ul>
If I check Fiddler, the data, in this case, the list is build correctly.
If I press F5 my data is displayed correctly.
I've read so many articles at this stage and I still haven't got a solution, one of them being View not updated after post and while I've tried ModelState.Clear(); and as you can see from my code I'm using #device.Name which is one of the suggestion. I'm not sure about the last one.
Another article I read was ASP NET MVC Post Redirect Get Pattern but again to no avail.
I'm obviously missing something.
Most articles/samples I've been looking at refer to posting via a Form and I know I'm posting, but is that the same as posting via a Form?
Also my page's viewModel is for my page and it contains a list of devices. Is that OK rather than passing the list of device as the viewmodel to the page? The reason I'm doing this is that I will want to access other lists at a later stage.
Has anyone got any suggestions?
Much appreciated.

ASP.NET MVC 3 Preview Image

I'm using MVC 3 and using the AjaxUpload plugin to upload an image using AJAX. I don't want to save the image in the file system, instead save it to the session object and then output the stream to populate an image control on the form? Would anyone know how to do this?
No idea why would ever want to do that (store the file in session) because if you have lots of users uploading their files at the same time, storing those files in the memory of your web server, especially if those files are big, won't make this server last very long. Storing the file on the filesystem is the recommended approach.
But anyway, here's how you could do it (assuming you didn't read or cared about my previous remark):
[HttpPost]
public ActionResult Upload(MyViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var buffer = new byte[model.File.InputStream];
model.File.InputStream.Read(buffer, 0, buffer.Length);
Session["uploadedFile"] = buffer;
return View(model);
}
where the File property on the view models is a HttpPostedFileBase. Next you could have a controller action which will serve this file:
public ActionResult Image()
{
byte[] buffer = (byte[])Session["uploadedFile"];
return File(buffer, "image/png");
}
and in the view you will have an <img> tag pointing to this action:
<img src="#Url.Action("image")" alt="" />
Now of course the AjaxUpload plugin allows you to upload the file using AJAX, so you don't need to reload the entire page. So in this case your controller action could simply return a JSON object to indicate whether the upload process succeeded and then in the success callback set the src property of the <img> tag to the controller action that will serve the file.
SomeView.cshtml:
<img src="#Url.Action("/Image/Render")" />
ImageController.cs:
public ActionResult Render() {
return File((byte[])Session["Avatar"], "image/jpeg")
}
Some example code. Modify it to whatever you want to do. Not really a good idea to sling an image into a session if lots of users. Better to stick it into a db if short lived, or if long lived, a more permanent storage (filesystem maybe).
public ActionResult UploadImage()
{
foreach (string imageName in Request.Files)
{
HttpPostedFileBase file = Request.Files[imageName];
if (file.ContentLength > 0)
{
BinaryReader br = new BinaryReader(file.InputStream);
byte[] content = br.ReadBytes(file.ContentLength);
Session[imageName] = content; // better to store in a db here
}
}
return View();
}
// return the image (controller action) /mycontroller/ViewImage?imageName=whatever
public FileStreamResult ViewImage(string imageName)
{
byte[] content = (byte[])Session[imageName] ; // where ever your content is stored (ideally something other than session)
MemoryStream ms = new MemoryStream(content);
return new FileStreamResult(ms, "application/octet-stream"); // set content type based on input image, it might be png, jpg, gif etc.,
}
Hope this helps.

Resources