How generate a unique file name at upload files in webserver (MVC) - asp.net-mvc

a have markup
<div>
#using (Html.BeginForm("Upload","Resume", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ #Html.AntiForgeryToken() <fieldset> <legend>Download Resume</legend> <div class="editor-field">
#Html.TextBox("file", "", new { type = "file" }) </div> <div class="editor-field">
<input type="submit" value="Upload" style="width: 120px; height: 25px; font-size: 1.1em; padding:0" />
</div> </fieldset> }
</div>
and Controller:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0) { var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/uploads"), fileName); file.SaveAs(path);
}
ViewBag.Message = "SuccessUpload";
return RedirectToAction("SuccessUpload", "Resume");
} catch
{ ViewBag.Message = "Fail";
return RedirectToAction("Upload"); }
}
How can generate unique file name at upload files, thanks for answers!

// change file name with its extension
var fileName = Guid.NewGuid().ToString() +
System.IO.Path.GetExtension(file.FileName);
var uploadUrl = Server.MapPath("~/uploads");
file.SaveAs(Path.Combine(uploadUrl, fileName));

One of the way is to concate current date.
var fileName = DateTime.Now.ToString("yyyymmddMMss") + System.IO.Path.GetExtension(file.FileName);

Related

How to show image name n edit view in ASP.NET MVC?

My issue is when I create a TextBox, it shows an image name but on type file it does not show its name and no file is chosen in it.
I want to show image name instead of "No file chosen".
public ActionResult userprofile(int? id)
{
var user = db.Personaltables.Find(id);
return View(user);
}
[HttpPost]
public ActionResult userprofile(Personaltable u, HttpPostedFileBase file, HttpPostedFileBase file1)
{
db.Entry(u).State = System.Data.Entity.EntityState.Modified;
if (file != null)
{
PersonaltableEntities db = new PersonaltableEntities();
string ImageName = System.IO.Path.GetFileName(file.FileName);
string physicalPath = Server.MapPath("~/Images/" + ImageName);
// save image in folder
file.SaveAs(physicalPath);
u.AttachPicture = ImageName;
}
using (PersonaltableEntities entity = new PersonaltableEntities())
{
var t = new Personaltable() // make variable of table
{
AttachPicture = u.AttachPicture,
};
db.SaveChanges();
}
return RedirectToAction("Index");
}
In Razor view:
#using (Html.BeginForm("userprofile", "personal", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-group">
<label class="label other">
Attach Picture
</label>
<div class="col-md-10">
#Html.EditorFor(model => model.AttachPicture, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
<input type="file" name="file" id="file" style="width: 100%;" data-val="true" data-val-required="File is required" /> <br />
#Html.ValidationMessageFor(model => model.AttachPicture, "", new { #class = "text-danger" })
</div>
</div>
}
Image name is stored in database and show in text box but in file type is empty
No file is chosen - why it is not stored in it?

Validation of the form submitted by Ajaxform jQuery plugin in ASP.NET MVC 5

public class File
{
[Key]
public int FileID { get; set; }
[Display(Name = "atachfile")]
[MaxLength(150)]
public string atachFile{ get; set; }
}
I wrote the controller codes of the editing section like this...
// GET: /Users/FileUpload/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
File file = db.Files.Find(id);
if (file == null)
{
return HttpNotFound();
}
return View(file);
}
// POST: /Users/FileUpload/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "FileID,atachFile")] File file, HttpPostedFileBase LearnAtach , int id)
{
if (ModelState.IsValid)
{
if (LearnAtach != null)
{
if (file.atachFile != null)
{
System.IO.File.Delete(Server.MapPath("/File/LearnAtach/" + file.atachFile));
}
string[] FileExtension = { ".zip" };
string FileType = Path.GetExtension(LearnAtach.FileName);
double FileSize = (LearnAtach.ContentLength / 1024.0) / 1024;
if (FileExtension.Contains(FileType.ToLower()))
{
if (FileSize > 950)
{/
ViewBag.sizeatach = "error..filexize>950";
return View(file);
}
file.atachFile = Guid.NewGuid() + Path.GetExtension(LearnAtach.FileName);
LearnAtach.SaveAs(Server.MapPath("/File/LearnAtach/" + file.atachFile));
}
else
{
ViewBag.typeatach = "filyType != zip";
this.TempData["UnSuccessMessage"] = "filyType != zip";
return View(file);
}
}
fileRepository.UpdateFile(file);
fileRepository.save();
return RedirectToAction("Index");
}
return View(file);
}
View markup:
#model DataLayer.File
#using (Html.BeginForm("Edit", "FileUpload", FormMethod.Post, new { enctype = "multipart/form-data", id = "fileform" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.FileID)
<div class="form-group">
#Html.LabelFor(model => model.atachFile, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.atachFile, new { type = "file", Name = "LearnAtach" })
#Html.ValidationMessageFor(model => model.atachFile)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="submit" class="btn btn-success" />
</div>
</div>
</div>
}
<div class="progress progress-striped" style="direction: ltr">
<div class="progress-bar progress-bar-success">0%</div>
</div>
<br /><br />
#section scripts
{
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/modal.js"></script>
<script>
$(document).ready(function() {
var bar = $('.progress-bar');
var percent = $('.progress-bar');
var status = $('#status');
$("#fileform").ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
//show preloder
},
success: function() {
var percentVal = '100%';
bar.width(percentVal);
percent.html(percentVal);
//hide preloder
$("#Success").modal();
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});
</script>
}
Now the file is uploaded but the validators are not applied .. How can I show the filesize limit and filetype the file on the client side to the user and apply
In fact, if the condition of file size and format is also wrong, the uploaded file will be saved in the (/File/LearnAtach)folder, but because the condition is incorrect, its path will not be stored in the database.
Also, if the condition is true, the condition whether this file already exists or deletes the previous one will not be checked. Thanks

Displaying List of Uploaded Files

I have a form where users can upload files and then view a list of their uploads. I'm running into two issues:
List of files isn't appearing when page loads. The SQL Query is valid.
When user uploads a file, a NullReferenceException because the file list model isn't being loaded. I'm not sure how to pass this model into view after the upload. Any advice is greatly appreciated.
Controller for fetching list of datasets is below. The controller for uploading datasets is different, of course, but it accepts an HttpPostedFileBase and a datasetName. It only returns ViewBag.error/ViewBag.message.
public ActionResult upload(DatasetViewModel model)
{
List<DatasetDetail> model2 = new List<DatasetDetail>();
var connectionstring = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(connectionstring))
try
{
// Your code
con.Open();
using (SqlCommand cmd = new SqlCommand("", con))
{
cmd.CommandText = "SELECT datasetid, datasetname, timestamp FROM datasets WHERE userid = #userid";
cmd.Parameters.Add("#userid", SqlDbType.Text);
cmd.Parameters["#userid"].Value = System.Web.HttpContext.Current.User.Identity.GetUserId();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
var u = new DatasetDetail();
u.datasetid = reader["datasetid"].ToString();
u.dataset = reader["datasetname"].ToString();
/* u.timestamp = Convert.ToDateTime(reader["TIMESTAMP"]);*/
model2.Add(u);
}
}
}
catch
{
// Catch exception
}
finally
{
// Close the connection
con.Close();
}
model.datasetlist = model2;
return View(model);
}
View:
#model WebApplication12.Models.DatasetViewModel
<div style="width: 320px;">
<h2>Manage Datasets</h2>
Download Excel Template
#using (Html.BeginForm("upload", "Dashboard", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary()
<div class="form-group">
<label>Dataset Name:</label>
<br />
<input type="text" id="datasetname" name="datasetname" />
</div>
<div class="form-group">
<input type="file" id="dataFile" name="upload" />
</div>
<div class="form-group">
<input type="submit" value="submit" class="btn btn-block" />
</div>
}
</div>
<div id="response"></div>
#if (ViewBag.Message != null)
{
<div class="alert alert-success" role="alert">#Html.Raw(ViewBag.Message)</div>
}
#if (ViewBag.Error != null)
{
<div class="alert alert-error" role="alert">#Html.Raw(ViewBag.Error)</div>
}
<div>
#foreach (var u in Model.datasetlist)
{
<b>u.dataset</b>
}
</div>
Relevant Models:
public class DatasetViewModel
{
public List<DatasetDetail> datasetlist { get; set; }
}
public class DatasetDetail
{
public string datasetid { get; set; }
public string dataset { get; set; }
/* public DateTime timestamp { get; set; }*/
}

Uploading image using json in aps mvc

I have a function for uploading selected files into folder in asp mvc4. The code in view page is
<form id="form1" method="post" enctype="multipart/form-data" action="EmployeeDetails/Upload">
<input type='file' id="imgInp" accept="image/jpeg"/>
<p>
<input type="submit" value="Upload" class="btn"/>
</p>
</form>
And the controller code is
[HttpPost]
public ActionResult Upload(HttpPostedFileBase imgInp)
{
if (imgInp != null && imgInp.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(imgInp.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/images/Profile"), fileName);
imgInp.SaveAs(path);
}
return view("Index");
}
Instead of this i want to send the image from view to controller as Json. Or is there any other methods to upload image without refreshing the view page..?
You can send form using ajax...
<form id="login-form">
<input type="file" name="photo" id="files" accept="image/*;capture=camera">
<button type="submit" onclick="submitform()">Submit</button>
</form>
jquery
function submitform(){
var postdata = $('#login-form').serialize();
var file = document.getElementById('files').files[0];
var fd = new FormData();
fd.append("files", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "/Home/Index", false);
xhr.send(fd);
}
controller
[HttpPost]
public JsonResult Index(FormCollection data)
{
if (Request.Files["files"] != null)
{
using (var binaryReader = new BinaryReader(Request.Files["files"].InputStream))
{
var Imagefile = binaryReader.ReadBytes(Request.Files["files"].ContentLength);//your image
}
}
}
uploading file to the server is quite simple. we need is a html form having encoding type set to multipart/form-data and a file input control.
View: NewProduct.cshtml
<form method="post" enctype="multipart/form-data">
<fieldset>
<legend>New Product</legend>
<div>
<label>Product Name:</label>
#Html.TextBoxFor(x => x.ProductName)
</div>
<div>
<label>Product Image:</label>
<input name="photo" id="photo" type="file">
</div>
<div>
#Html.ValidationSummary()
</div>
<input type="submit" value="Save" />
</fieldset>
</form>
The uploaded files are available in HttpFileCollectionBase of Request.Files.
controller:
[HttpPost]
public ActionResult NewProduct()
{
HttpPostedFileBase image = Request.Files["photo"];
if (ModelState.IsValid)
{
if (image != null && image.ContentLength > 0)
{
var fileName = Path.GetFileName(image.FileName);
string subPath = Server.MapPath("ProductLogo");
bool isExists = System.IO.Directory.Exists(subPath);
if (!isExists)
System.IO.Directory.CreateDirectory(subPath);
var path = Path.Combine(subPath+"\\", fileName);
if (System.IO.File.Exists(path))
{
var nfile = DateTime.Now.ToString() + "_" + fileName;
path = Path.Combine(subPath+"\\", nfile);
}
file.SaveAs(path);
return RedirectToAction("List", "Product");
}
else
{
ModelState.AddModelError("", "Please Select an image");
return View();
}
}
else
{
return View();
}
}

File uploading in MVC 4

I simply tried this, but its not working, what is the problem in it,
MY index page:
#{
ViewBag.Title = "Index";
}
#using (Html.BeginForm("Upload", "Home", FormMethod.Post, new { enctype = "multipart/from- data" }))
{
<div>
<h1 style="align-content: center; color: blueviolet">Application to upload files</h1>
</div>
<div>
<input type="file" id="file" name="file" />
<br />
<input type="submit" id="load" name="submit" value="Submit" />
</div>
}
And My controller is,
[HttpPost]
public ActionResult Upload()
{
string path = #"~/Content/Upload";
HttpPostedFileBase file = Request.Files["file"];
if (file != null)
file.SaveAs(path + file.FileName);
return Content("Sucess");
}
The path you are attempting to save your file to looks wrong. Try with MapPath:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
string path = Server.MapPath("~/Content/Upload");
if (file != null)
{
file.SaveAs(Path.Combine(path, file.FileName));
}
return Content("Sucess");
}
Also make sure that you have used the correct enctype attribute in your form:
enctype = "multipart/form-data"
instead of:
enctype = "multipart/from- data"

Resources