ASP.NET has many different upload approaches. Thus, it is best to choose the one that best suits your needs, whether it is uploading a few files from one or more files at a time, working with small or very large files, only Sending entire folders or files, uploading a simple image beforehand or preprocessing pictures.
In this article, we consider various methods of file upload in ASP.NET MVC i.e Upload file and JSON data in the same POST request using jquery ajax and discuss their use, but let’s grab how file upload input control works in general.
The file upload process is quite simple. There are always two parts, the client and server sides, that communicate with each other via HTTP requests and responses.
- Now Add a controller “Home” in the Project and also add an action method in it.
- Right Click in the Action Method and add a View
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace UploadingFileMvc.Controllers
{
public class FilesInoformation
{
public string filename { get; set; }
public string filepath { get; set; }
}
public class FileUploadController : Controller
{
// GET: FileUpload
// GET: Home
public ActionResult Index()
{
//getting the list of file uploaded
DirectoryInfo directory = new DirectoryInfo(Server.MapPath(@"~\PdfFiles"));
var files = directory.GetFiles().ToList();
List<FilesInoformation> model = new List<FilesInoformation>();
foreach (var file in files)
{
model.Add(new FilesInoformation { filename = file.Name, filepath = "/PdfFiles/" + file.Name });
}
return View(model);
}
//For Uploading Multiple files at once
[HttpPost]
public ActionResult UploadMultiplePdfFiles()
{
//getting form data
string username = Request.Form["Username"];
string userId = Request.Form["UserId"];
if (Request.Files.Count > 0) // Checking if Request object has file
{
try
{
HttpFileCollectionBase files = Request.Files;
//in case if you want upload the multiple pdf files
for (int i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
string fname = file.FileName;
// Get the complete folder path and store the file inside it.
fname = Path.Combine(Server.MapPath("~/PdfFiles/"), fname);
file.SaveAs(fname);
}
return Json("Pdf Uplaoded Successfully!");
}
catch (Exception ex)
{
return Json(ex.Message);
}
}
else
{
return Json("No files selected.");
}
}
}
}
View Htm Code
@model IEnumerable<UploadingFileMvc.Controllers.FilesInoformation>
@{
ViewBag.Title = "";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
@using (Html.BeginForm("UploadPdf", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<fieldset>
<legend>Upload a Pdf file By Ajax</legend>
<div class="editor-field">
@Html.TextBox("pdffile", "", new { type = "file", accept = "application/pdf" })
</div>
<br />
<br />
<div class="editor-field">
<input type="button" id="btnfileUpload" value="Upload Pdf" />
</div>
<div class="row">
<h3>Uploaded Filles</h3>
<table class="table">
<thead>
<tr>
<th>FileName</th>
<th>Action</th>
</tr>
</thead>
@if (Model != null)
{
foreach (var file in Model)
{
<tr>
<td>@file.filename</td>
<td><a href="@file.filepath">View Pdf</a></td>
</tr>
}
}
</table>
</div>
</fieldset>
<script>
$(document).ready(function(){
$('#btnfileUpload').click(function () {
if (window.FormData !== undefined) {
var fileUpload = $("#pdffile").get(0);
var files = fileUpload.files;
var fileData = new FormData();
fileData.append('Username', 'testuser');
fileData.append('UserId', '1');
for (var i = 0; i < files.length; i++) {
fileData.append(files[i].name, files[i]);
}
$.ajax({
url: '/FileUpload/UploadMultiplePdfFiles',
type: "POST",
contentType: false,
processData: false,
data: fileData,
success: function (result) {
alert(result);
window.location.reload();
},
error: function (err) {
alert(err.statusText);
}
});
} else {
alert("Your browser doesn support FormData");
}
});
});
</script>
}
If you have any questions related to the post please comment.
Please also share this article to Facebook, Twitter, Reddit, and other social media platform to help developers who face the same issue.
Please like our Facebook and follow us on Twitter for the latest update on technology or any support.
The post [Solved]-Uploading both data and files in FormData using Ajax MVC appeared first on Software Development | Programming Tutorials.
Read More Articles
- Write a value which contain comma to a CSV file in c#?
- Reading CSV File with cells containing commas c#
- Split CSV with columns may contain ‘,’ Comma C#
- [Simple Way]-Cascading DropDownList in Asp.Net Mvc Using Jquery Ajax
- [Simple Way]-How to get data from database using JQuery Ajax in asp net MVC
- [Simple Way]-ASP.NET Core Upload Multiple File Web API model
- [Simple Way]- Image Upload in .NET Core Web API
- [Easy Way]-Receive File and other form data together in ASP.NET Core Web API
- Replace image in word document using C#
- How to add new rows to an existing word document table in C#
- how to download a file from url and save in location using unity3d in C sharp?
- .NET Core 3 MVC download a file from HTTP and re-deliver to client using minimum memory
- How to view PDF document in MVC and not download it directly?
- How can I create and display a PDF file for a .net core MVC web application?
- Upload file with .net core MVC using ajax and pass as model
- How to get data from third party rest API in MVC 6.0 and asp net core application
- How can I upload a file using AsyncFileUpload and save the bytes in database?
- How to download edited PDF using ITextSharp and C# Blazor
- How to download file from bytes by using web api and angular
- How to Download file from one FTP and then Upload file to different FTP?
- How to get FileName and upload file in asp.net JQuery without using File Upload
- How to download pdf file using asp.net?
- How do I log into a "Flash Website" with WebClient and download a file using c# ?
- How to measure upload and download internet speed with silverlight and ASP.NET MVC
- How do I measure the upload and download bandwidth utilization per each process on windows xp/2003/2008 in realtime using C#?
- How download file form azure DevOps sever to a specified path using API and c#
- How to download a file and and stay in current page in MVC
- How do I modify PDF without a library using C# and stream it back to client in ASP.NET?
- How can I load a sound file into memory using NAudio and use it later?
- How to add a folder to a folder when creating a zip file in asp using Ionic.Zip
- How to add header and footer in all page of pdf using iTextsharp version 5.2.0 in C#
- how to parse json data from a rest api using C# in the ASP.Net Core MVC model and display it on a HTML page
- SSH.NET: Is it possible to upload files using SFTP and preserve the file dates from source files?
- How to show a message and send a file using ASP.NET
- How to download and unzip a sitemap gz file in c#?
- How can I calculate and display download speed using webclient?
- How to upload base64 pdf to S3 with dotnet SDK using PutObjectAsync
- How to create download feature using ASP.NET Core 2.1 and React JS?
- How can I structure an ASP.NET MVC application with a "Core" database and individual derived databases using Entity Framework?
- How to find whether a PDF file has overlapping text or not, using c#
- Expression.ToString() with format provider
- What is the equivalent of a C# gridview in java GUI?
- c# emgu.cv trying to copy mat.Data returnl null
- Recording and saving sounds from applications?
- Building a class that behaves like Nullable<T>
- Iterate a collection of models to save multiple records in MVC
- How to add public property to custom SqlMembership Provider to be configured in web.config
- Queuing Async Function Calls
- WPF Storyboard with TranslateTransform
- Adding row details to DataGrid in XAML
- ASP.NET MVC Session State Timeout
- 'System.OutOfMemoryException' while sending large amount of data to webservice c#
- Microsoft jet database engine cannot open the file.''. It is already opened exclusively by another user, or you need permission
- How to deserialize xml to derived classes base on element's value?
- How to check if List < int[ ] > contains an int[] element that store the same values as another int[ ]?
- Convert to DateTime
- How to use math to create more efficient code?
- Cannot reproduce in tests the exception Cannot consume scoped service from singleton outside Mvc framework
- We can't create an object in interface but how a return type can be a interface?
- How to display a text as bold in a datagrid?