This is my View
Test Upload File
<form action="#Url.Action("Index", "Home")" method="post" enctype="multipart/form-data">
#Html.AntiForgeryToken()
<label for="file">Filename:</label>
<input type="file" name="files" id="files" />
<input type="submit" name="submit" value="Upload" />
</form>
This is my Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
try
{
if (file != null && file.ContentLength > 0)
{
var fileName = file.FileName;
var path = Path.Combine(Server.MapPath(#"\Upload"), fileName);
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
}
}
return View();
}
The problem is the HttpPostedFileBase files is always null. I cant find the problem.
Here is an example how to use form onsubmit method
Your HTML part
<form id="formTest" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="files" id="files" />
<input type="submit" name="submit" value="Upload" />
</form>
script
<script type="text/javascript">
var form = document.getElementById('formTest').onsubmit = function (e) {
e.preventDefault();
var formdata = new FormData(); //FormData object
var fileInput = document.getElementById('files');
if (fileInput != "" && fileInput.files.length > 0) {
//Iterating through each files selected in fileInput
for (i = 0; i < fileInput.files.length; i++) {
//Appending each file to FormData object
formdata.append(fileInput.files[i].name, fileInput.files[i]);
}
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
var url = '#Url.Action("Index","Home")';
xhr.open('POST', url);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var result = xhr.responseText;
}
}
return false;
}
}
</script>
C#
public ActionResult Index()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
return View();
}
}
You can also handle files with Request.Files like this:
public ActionResult Index()
{
if (Request.Files.Count > 0)
{
var file = Request.Files[0];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
file.SaveAs(path);
}
}
}
And for your second question, please try to use it between Html.BeginForm instead of form like this:
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<label>Filename:</label>
<input type="file" name="file1"/>
<input type="submit" name="submit" value="Upload" />
}
Related
I use asp.net core razor pages to create my application, in my create page, I have two file controls, one for upload icon image and the other for uploading detail images. But when I click edit button, all of the fields were initialized, except the two file controls. Please check my code. Anyone can help?
In my razor page:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label asp-for="Product.Icon" class="control-label"></label>
<input asp-for="#Model.Icon" type="file" />
<span asp-validation-for="Product.Icon" class="text-danger"></span>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label class="control-label”>Detail Images(support multi-uploading):</label>
<input type="file" id="fUpload" name="files" multiple />
</div>
</div>
</div>
In my page model:
public async Task<IActionResult> OnGetAsync(int? id)
{
if (id == null)
{
return NotFound();
}
Product = await _context.Products
.Include(p => p.Shop).SingleOrDefaultAsync(m => m.ID == id);
if (Product == null)
{
return NotFound();
}
ViewData["Shop"] = new SelectList(_context.Shops, "ID", "Name");
return Page();
}
public async Task<IActionResult> OnPostAsync(List<IFormFile> files)
{
if (!ModelState.IsValid)
{
return Page();
}
var uploads = Path.Combine(hostingEnvironment.WebRootPath, "uploads");
if (!Directory.Exists(uploads))
{
Directory.CreateDirectory(uploads);
}
if (this.Icon != null)
{
var fileName = GetUniqueName(this.Icon.FileName);
var filePath = Path.Combine(uploads, fileName);
this.Icon.CopyTo(new FileStream(filePath, FileMode.Create));
this.Product.Icon = fileName;
}
if (files != null && files.Count > 0)
{
foreach (IFormFile item in files)
{
if (item.Length > 0)
{
var fn = GetUniqueName(item.FileName);
var fp = Path.Combine(uploads, fn);
item.CopyTo(new FileStream(fp, FileMode.Create));
this.Product.ProductImages = this.Product.ProductImages + fn + "^";
}
}
}
_context.Attach(Product).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!ProductExists(Product.ID))
{
return NotFound();
}
else
{
throw;
}
}
return RedirectToPage("./Index");
}
The most important part of your page is missing from the code you provided - the <form> tag. For file uploading to work, you must specify that the method is post and you must also provide an enctype attribute with its value set to multipart/form-data:
<form method="post" enctype="multipart/form-data">
...
Ref: https://www.learnrazorpages.com/razor-pages/forms/file-upload
I'm trying to make a website using asp.net mvc 4 where I can store data in MSSQL db & store uploaded image files in local storage. So far data is storing successfully but whenever I select multiple images to upload, it only uploads the first selected image only. Here are my codes,
Controller
[HttpPost]
public ActionResult FlatManager(FlatMgt FlatTable, HttpPostedFileBase[] files)
{
if (Session["username"] != null)
{
if (ModelState.IsValid)
{
var AddFlat = FlatTable.Flats;
db.FlatInfoes.Add(AddFlat);
db.SaveChanges();
foreach (HttpPostedFileBase file in files)
{
if (file != null && file.ContentLength > 0)
{
int imageCount = 0;
string picName = FlatTable.Flats.flatno.ToString() + "-" + imageCount;
string picExt = Path.GetExtension(file.FileName);
if (picExt == ".jpg" || picExt == ".gif" || picExt == ".jpeg")
{
picExt = ".png";
}
string path = System.IO.Path.Combine(Server.MapPath("~/Images/"), picName + picExt);
file.SaveAs(path);
imageCount++;
using (MemoryStream ms = new MemoryStream())
{
file.InputStream.CopyTo(ms);
byte[] array = ms.GetBuffer();
}
}
else
{
TempData["add_fail"] = "Error! Wrong File Type(s)! Please Try Again.";
return RedirectToAction("FlatManager");
}
}
TempData["add_success"] = "Information Added Successfully!";
return RedirectToAction("FlatManager");
}
else
{
TempData["add_fail"] = "Error! Please Provide Valid Information.";
return RedirectToAction("FlatManager");
}
}
else
{
return RedirectToAction("Login");
}
}
View
#using (Html.BeginForm("FlatManager", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<label for="file">Upload Image:</label>
<input type="file" multiple="multiple" name="files" id="file" style="width: 100%;" /><br />
<input type="submit" value="Add" />
}
I can't find any error in my codes. How can I solve this problem? Will be really helpful if someone helps. Thanks.
I have file upload html code as:
#using (Ajax.BeginForm("UploadImage", "PP", new AjaxOptions() { HttpMethod = "POST" }, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<input type="file" name="files">
<button class="buttoncss">Upload</button>
//<input type="submit" name="Submit to server">
(also tried with input type="submit"
}
In PPController i have method as below:
[HttpPost]
[ValidateAntiForgeryToken]
public void UploadImage(IEnumerable<HttpPostedFileBase> files)
{
if (files != null)
{
foreach (var file in files)
{
// Verify that the user selected a file
if (file != null && file.ContentLength > 0)
{
// extract only the fielname
var fileName = Path.GetFileName(file.FileName);
// TODO: need to define destination
var path = Path.Combine(Server.MapPath("~/Upload"), fileName);
file.SaveAs(path);
}
}
}
But my controller method is not getting called.
What can be the problem?
Please help me.
i am doing my project in mvc4 using c#
i my project i want to upload two image files from a folder so i use the following code.
View:
<form action="" method="post" enctype="multipart/form-data">
<label for="file1">Filename:</label>
<input type="file" name="files" id="file1" />
<label for="file2">Filename:</label>
<input type="file" name="files" id="file2" />
<input type="submit" />
</form>
Controller:
[HttpPost]
public ActionResult Index(IEnumerable<HttpPostedFileBase> files) {
foreach (var file in files) {
if (file.ContentLength > 0) {
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder1"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
actually my need is that i want to upload these images in different folders on a single submit button. (That is file1 into Folder1 and file2 into Folder2) is that possible??
You have many solutions.
public ActionResult Index(IEnumerable<HttpPostedFileBase> files)
{
IList<HttpPostedFileBase> list = (IList<HttpPostedFileBase>)files;
for (int i = 0; i < files.Count(); i++)
{
if (list[i].ContentLength > 0 && i == 0)
{
var fileName = Path.GetFileName(list[i].FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder1"), fileName);
file.SaveAs(path);
}
else if (list[i].ContentLength > 0)
{
var fileName = Path.GetFileName(list[i].FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/Folder2"), fileName);
file.SaveAs(path);
}
}
return RedirectToAction("Index");
}
i am trying to upload files with the jqueryform plugin. I have to file upload controls but the second one cant upload?
<div>
<h2>
Upload test</h2>
<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script src="../../Scripts/jquery-ui-1.8.12.custom.min.js" type="text/javascript"></script>
<script src="../../Scripts/jqueryform.js" type="text/javascript"></script>
<script src="../../Scripts/jblock.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function (event) {
$(function () {
$("#ajaxUploadForm").ajaxForm({
iframe: true,
dataType: "json",
beforeSubmit: function () {
$("#ajaxUploadForm").block({ message: ' Uploading Image' });
},
success: function (result) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
//$.growlUI(null, result.message);
if (result.message != 'Success') {
alert(result.message);
}
else {
}
},
error: function (xhr, textStatus, errorThrown) {
$("#ajaxUploadForm").unblock();
$("#ajaxUploadForm").resetForm();
}
});
});
});
</script>
<form id="ajaxUploadForm" action="<%= Url.Action("Upload", "Home")%>" method="post"
enctype="multipart/form-data">
<input type="file" name="file" />
<input type="file" name="file2" />
<input id="ajaxUploadButton" type="submit" value="upload file" />
</form>
</div>
public ActionResult Index()
{
return View();
}
public FileUploadJsonResult Upload(HttpPostedFileBase file)
{
if (file == null)
{
return new FileUploadJsonResult { Data = new { message = "error" } };
}
if (file.ContentLength > 0)
{
//save file or something
}
return new FileUploadJsonResult { Data = new { message = string.Format("success") } };
}
public class FileUploadJsonResult : JsonResult
{
public override void ExecuteResult(ControllerContext context)
{
this.ContentType = "text/html";
context.HttpContext.Response.Write("<textarea>");
base.ExecuteResult(context);
context.HttpContext.Response.Write("</textarea>");
}
}
You have two file inputs on your form named respectively file and file1. You controller action that handles the upload has only a single HttpPostedFileBase argument named file. So you could add a second one:
public FileUploadJsonResult Upload(
HttpPostedFileBase file,
HttpPostedFileBase file1
)
{
if (file == null || file1 == null)
{
return new FileUploadJsonResult { Data = new { message = "error" } };
}
if (file.ContentLength > 0)
{
//save file or something
}
if (file1.ContentLength > 0)
{
//save the second file or something
}
return new FileUploadJsonResult { Data = new { message = string.Format("success") } };
}
Or if you wanted to handle multiple files you could give them the same name on your form:
<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
<input type="file" name="files" />
...
and your controller action could then take a list of files:
public FileUploadJsonResult Upload(IEnumerable<HttpPostedFileBase> files)
{
if (files)
{
return new FileUploadJsonResult { Data = new { message = "error" } };
}
foreach (var file in files)
{
if (file.ContentLength > 0)
{
//save file or something
}
}
return new FileUploadJsonResult { Data = new { message = string.Format("success") } };
}
You may checkout the following blog post about uploading files in ASP.NET MVC.