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 resize and save an image which uploaded using file upload control in c#
- How to Download the File using HttpWebRequest and HttpWebResponse class(Cookies,Credentials,etc.)
- How can I upload a file and form data using Flurl?
- How to implement file download with AJAX and MVC
- How can I upload a file and save it to a Stream for further preview using C#?
- How to Download a PDF file from Azure in ASP.NET MVC via Save Dialog
- Download and display a private Azure Blob using ASP MVC
- How to download multiple files using asp and C#
- How to upload files using NET CORE and Refit
- How to open PDF file in a new tab or window instead of downloading it using C# and ASP.NET MVC?
- How to insert and read a pdf file to Sql Server 2005 database using C#
- Download PDF file With FTP using XMLHttpRequest and generic handler
- Download file of any type in Asp.Net MVC using FileResult?
- How to find the most recent file in a directory using .NET, and without looping?
- ASP.NET WebApi: how to perform a multipart post with file upload using WebApi HttpClient
- How to upload a file to amazon S3 super easy using c#
- How to sync model after using Code First from Database using Entity Framework 6.1 and MVC 5?
- How to programmatically print to PDF file without prompting for filename in C# using the Microsoft Print To PDF printer that comes with Windows 10
- How can one generate and save a file client side using Blazor?
- How do you clear cookies using asp.net mvc 3 and c#?
- How can I sign a file using RSA and SHA256 with .NET?
- What is difference between RegAsm.exe and regsvr32? How to generate a tlb file using regsvr32?
- How to upload large files using MVC 4?
- How do I resolve Web API controllers using Autofac in a mixed Web API and MVC application?
- ASP Core WebApi Test File Upload using Postman
- How to Unzip all .Zip file from Folder using C# 4.0 and without using any OpenSource Dll?
- How to check if a file exists on a server using c# and the WebClient class
- How do you download and extract a gzipped file with C#?
- ASP NET MVC 5 Delete File From Server
- In MVC 2, How would you determine a file exists at the server using C#?
- Validating Recaptcha 2 (No CAPTCHA reCAPTCHA) in ASP.NET's server side
- How to handle empty column in parsing with CsvHelper?
- How do I efficiently get a subset of a byte array (first N elements) in C#?
- Dependency injection with interfaces or classes
- C#: How to effectively filter (hide) ListView Items while in virtual mode?
- Get the AspNetUser from HttpContext.Current.User
- Is returning a Task violating the CQS-principle?
- JS bundles do not render without EnableOptimization set to true
- Which one should I use? decimal.Add() or "+"
- MSTest + CHESS in VS 2010
- Using specific patterns to implement interfaces
- ObservableCollection and threading
- C# List Generic Extension Method vs Non-Generic
- BlankPage constructor cannot initialize components
- Date vs DateTime
- Why does this executables icon look bad when the icon itself doesn't?
- Can I "multiply" a string (in C#)?
- Word Wrapping with Regular Expressions
- Succinct introduction to C++/CLI for C#/Haskell/F#/JS/C++/... programmer
- Why is FileStream not closed by XmlReader