access input value in webAPI from post - c#

I use the following code to upload files using a webAPI, the file upload part works fine but how can I access all additional input values and hidden input values from the post?
[HttpPost]
public async Task<object> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent("form-data"))
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.UnsupportedMediaType));
}
var streamProvider = new MultipartFormDataStreamProvider(HttpContext.Current.Server.MapPath("~/App_Data/Temp/"));
try
{
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (MultipartFileData fileData in streamProvider.FileData)
{
var fileName = "";
if (string.IsNullOrEmpty(fileData.Headers.ContentDisposition.FileName))
{
fileName = Guid.NewGuid().ToString();
}
fileName = fileData.Headers.ContentDisposition.FileName;
if (fileName.StartsWith("\"") && fileName.EndsWith("\""))
{
fileName = fileName.Trim('"');
}
if (fileName.Contains(#"/") || fileName.Contains(#"\"))
{
fileName = Path.GetFileName(fileName);
}
File.Move(fileData.LocalFileName, Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/"), Path.GetDirectoryName(fileName) + Guid.NewGuid() + Path.GetExtension(fileName)));
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
And here is the form I am using for posting the file.
<form name="form1" method="post" enctype="multipart/form-data" action="api/upload">
<div>
<label for="caption">Image Caption</label>
<input name="caption" type="text" />
</div>
<div>
<input type="hidden" value="secretvalue"/>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>

Related

An item with the same key has already been added. Key: [0, SEX]

When I am trying to import an excel more than 33 columns I have this error.
An item with the same key has already been added. Key: [0, SEX]
[0,SEX] is my 34th column
I am converting file to an Isheet object. It's working fine when it's under 33 columns.
Also It's working on a different project. I am using it exactly same way here too. I checked versions of some packages but couldn't find the problem.
This is my controller.
public async Task<IActionResult> YeniUyeAktarimUpload()
{
try
{
IFormFile file = Request.Form.Files[0];
string folderName = "UploadExcel";
string webRootPath = _hostingEnvironment.WebRootPath;
string newPath = Path.Combine(webRootPath, folderName);
Stream stream = file.OpenReadStream();
using (stream)
{
ISheet sheet;
string sFileExtension = Path.GetExtension(file.FileName).ToLower();
if (sFileExtension == ".xls")
{
HSSFWorkbook hssfwb = new HSSFWorkbook(stream); //This will read the Excel 97-2000 formats
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
else
{
XSSFWorkbook hssfwb = new XSSFWorkbook(stream); //I GET ERROR HERE
sheet = hssfwb.GetSheetAt(0); //get first sheet from workbook
}
}
await _aktarimlarService.YeniUyeAktarim(sheet);
return RedirectToAction("YeniUyeAktarim","Aktarimlar");
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
TempData["ErrorMessage"] = "Duyurular getirilirken hata oluştu. Lütfen daha sonra tekrar deneyiniz. ";
return RedirectToAction("Error", "HomeKurum", new { returnUrl = "/Aktarimlar/YeniUyeAktarim" });
}
}
and this is my view
<section class="content">
<div class="card card-primary card-outline">
<div class="card-header">
<h2 class="card-title">Yeni Üye Aktarım</h2>
</div>
<!-- /.card-header -->
<div class="card-body">
<form asp-controller="Home" asp-action="Export">
<div class="container">
<div class="row">
<div class="col-md-4">
<input type="file" id="fileupload" name="files" class="form-control" />
</div>
<div class="col-md-3">
<input type="button" name="Upload" value="Upload" id="btnupload" class="btn btn-primary" />
Download
</div>
<div class="col-md-5">
<input type="submit" name="Export" value="Create and Export" id="btnExport" class="btn btn-primary" asp-action="Export" />
</div>
</div>
<div class="clearfix"> </div>
<div class="row">
<div id="divPrint"></div>
</div>
</div>
</form>
<a class="text-danger" href="~/Downloads/AKTARIM_TASLAK/YeniUyeAktarim.xlsx">Taslak indir</a>
<img width="50" height="40" src="~/images/excel-indir.png" />
#if (TempData.ContainsKey("ErrorMessage"))
{
<div class="alert alert-danger alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
#TempData["ErrorMessage"]
</div>
}
</div>
</div>
And this is my jquery code
<script type="text/javascript">$(function () {
$('#btnupload').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file.");
return false;
}
else {
var extension = filename.replace(/^.*\./, '');
if ($.inArray(extension, fileExtension) == -1) {
alert("Please select only excel files.");
return false;
}
}
var fdata = new FormData();
var fileUpload = $("#fileupload").get(0);
var files = fileUpload.files;
fdata.append(files[0].name, files[0]);
$.ajax({
type: "POST",
url: "/Aktarimlar/YeniUyeAktarimUpload",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: fdata,
contentType: false,
processData: false,
success: function (response) {
if (response.length == 0)
alert('Some error occured while uploading');
else {
$('#divPrint').html(response);
}
},
error: function (e) {
$('#divPrint').html(e.responseText);
}
});
})
$('#btnExport').on('click', function () {
var fileExtension = ['xls', 'xlsx'];
var filename = $('#fileupload').val();
if (filename.length == 0) {
alert("Please select a file then Import");
return false;
}
});
});</script>
Thanks for your help..

adding photo and model

I am new to asp.net core. I am facing a problem when uploading a file(image) with my model.
the viewmodel :
namespace WebApplication1.ViewModels
{
public class HotelViewModel
{
public String NomHotel { get; set; }
public String NomAgence { get; set; }
public String Filepath{ get; set; }
}
}
this is the cshtml :
#model WebApplication1.ViewModels.HotelViewModel
<form novalidate method="post" enctype="multipart/form-data" asp-
controller="Hotel" asp-action="Hotel">
<div id="parent">
<div id="wide" class="col-lg-4">
<div asp-validation-summary="ModelOnly"></div>
<div class="form-group">
<label asp-for="NomHotel"></label>
<input asp-for="NomHotel" class="form-control" />
<span asp-validation-for="NomHotel"></span>
</div>
<div class="form-group">
<label asp-for="NomAgence"></label>
<input asp-for="NomAgence" class="form-control" />
<span asp-validation-for="NomAgence"></span>
</div>
<div class="col-md-10">
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple class="btn" />
</div>
<div id="#rest">
<div class="form-group">
<input type="submit" value="Ajouter" class="btn btn-lg btn-
success ahbat" />
</div>
</div>
</div>
</div>
and this is the controller :
[HttpPost]
public IActionResult Hotel(HotelViewModel mod)
{
Hotel hotel = new Hotel
{
NomAgence = mod.NomAgence,
NomHotel = mod.NomHotel
};
var newFileName = string.Empty;
if (HttpContext.Request.Form.Files != null)
{
var fileName = string.Empty;
string PathDB = string.Empty;
var files = HttpContext.Request.Form.Files;
foreach (var file in files)
{
if (file.Length > 0)
{
//Getting FileName
fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
//Assigning Unique Filename (Guid)
var myUniqueFileName = Convert.ToString(Guid.NewGuid());
//Getting file Extension
var FileExtension = Path.GetExtension(fileName);
// concating FileName + FileExtension
newFileName = myUniqueFileName + FileExtension;
// Combines two strings into a path.
fileName = Path.Combine(_environment.WebRootPath, "HotelImg") + $#"\{newFileName}";
// if you want to store path of folder in database
PathDB = "demoImages/" + newFileName;
hotel.Piscine = newFileName;
using (FileStream fs = System.IO.File.Create(fileName))
{
file.CopyTo(fs);
fs.Flush();
}
}
}
}
IH.Create(hotel);
return View();
}
as said I have tried different combinations of code but I always get the file or the model never both and I need both of them. This is the most correct code I can show you sorry if it is not too clear.

ASP.NET Razor File Upload

I'm following this example on the MS website for File Uploads using Razor and C#.
If I have more than one File upload buttons, how would the C# code know which button the uploaded file is from? Based on the button the file was uploaded from, I will be saving files to specific folders.
https://learn.microsoft.com/en-us/aspnet/web-pages/overview/data/working-with-files
#using Microsoft.Web.Helpers;
#{
var fileName = "";
if (IsPost) {
var fileSavePath = "";
var uploadedFile = Request.Files[0];
fileName = Path.GetFileName(uploadedFile.FileName);
fileSavePath = Server.MapPath("~/App_Data/UploadedFiles/" +
fileName);
uploadedFile.SaveAs(fileSavePath);
}
}
<!DOCTYPE html>
<html>
<head>
<title>FileUpload - Single-File Example</title>
</head>
<body>
<h1>FileUpload - Single-File Example</h1>
#FileUpload.GetHtml(
initialNumberOfFiles:1,
allowMoreFilesToBeAdded:false,
includeFormTag:true,
uploadText:"Upload")
#if (IsPost) {
<span>File uploaded!</span><br/>
}
</body>
</html>
The way to do this is to name the buttons the same, but give them different values. You can then do a case statement and direct the logic based on the value.
Razor
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="FirstUpload" />
<input type="submit" name="submitID" id="submitID" value="Upload1" />
<input type="file" name="SecondUpload" />
<input type="submit" name="submitID" id="submitID" value="Upload2" />
}
Controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(FormCollection collection)
{
string btn = Request.Params["submitID"];
switch (btn)
{
case "Upload1":
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
}
break;
case "Upload2":
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
}
break;
}
return View();
}
I had a similar problem and ended up with following code:
Razor
//BeginForm and other staff
#foreach (var d in Model.Types)
{
<input type="file" name="doc:#d.Id:upload" />//#d.Id is the key point
<button formenctype="multipart/form-data"
type="submit" formaction="/MyController/uploaddoc"
name="typeid" formmethod="post" value="#d.Id">//this way I send Id to controller
Upload
</button>
}
MyController
[HttpPost]
[ValidateAntiForgeryToken]
[Route("mycontroller/uploaddoc")]//same as formaction
public async Task<ActionResult> UploadDoc(FormCollection data, int typeid)
{
//restore inpput name
var fl = Request.Files["doc:" + typeid.ToString() + ":upload"];
if (fl != null && fl.ContentLength > 0)
{
var path = Server.MapPath("~/app_data/docs");
var fn = Guid.NewGuid().ToString();//random name
using (FileStream fs = System.IO.File.Create(Path.Combine(path, fn)))
{
await fl.InputStream.CopyToAsync(fs);
}
}
}

File is not uploading in ASP.Net MVC

Hi to all of you I am facing a problem on uploading a file and saving it into a folder here is my view
<div class="admin-empty-dashboard">
#using (Html.BeginForm("UploadResumes", "Employee", new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="icon">
<i class="ion-ios-book-outline"></i>
</div>
<h4>Welcome #Model.FullName!</h4>
<p>#ViewBag.Error</p>
<div class="form-group bootstrap-fileinput-style-01">
<label>Upload Resume</label>
<input type="file" name="file" required="required" class="btn btn-primary" style="margin-left:265px" accept="application/msword,text/plain, application/pdf">
<span class="font12 font-italic">** File must not bigger than 2MB</span>
</div>
<input type="submit" name="name" class="btn btn-primary" value="UploadResumes" />
}
</div>
and here is my controllers action problem is that it HttpPostedFileBase object value is always null and i ran Request.Files.Count it's also giving me zero where is problem?
public ActionResult UploadResumes(HttpPostedFileBase file)
{
if (Session["UserID"] != null && Session["UserName"] != null && Session["EmployeeID"] != null)
{
int id = Convert.ToInt32(Session["EmployeeID"]);
string[] allowedExtenssions = new string[] { ".pdf", ".doc", ".docx" };
string cvPath = "~/cvs/Employee_cvs/";
if (!Directory.Exists(Server.MapPath(cvPath)))
Directory.CreateDirectory(Server.MapPath(cvPath));
MyDbContext db=new MyDbContext();
tblEmployee employee = (from s in db.tblEmployees where s.UserId == id select s).FirstOrDefault();
// HttpPostedFileBase cv = Request.Files["CV"];
if (file != null)
{
if (file.ContentLength > 0)
{
string ext = Path.GetExtension(file.FileName);
if (allowedExtenssions.Contains(ext.ToLower()))
{
string fileName = DateTime.Now.Ticks + ext;
string filePath = cvPath + fileName;
string serverPath = Server.MapPath(filePath);
file.SaveAs(serverPath);
employee.cvUrl = filePath;
}
}
ViewBag.Error = "Some Error Occured";
}
return RedirectToAction("Dashboard");
}
else
{
return RedirectToAction("Login", "User");
}
}
Update like below and check
#using (Html.BeginForm("UploadResumes", "Employee",FormMethod.Post, new { enctype = "multipart/form-data" }))
{
}
Also
[HttpPost]
public ActionResult UploadResumes(HttpPostedFileBase file)
{
}
Try changing your parameters on your controller to
public ActionResult UploadResumes(Model yourModel, HttpHostedFileBase file)
In most of my controllers that require a file for upload, are usually array based. Make you function parameters an array like this:
public ActionResult UploadResumes(HttpPostedFileBase[] files){
}

Asp.NET MVC 4 Ajax Request Cancels on Submit

Issue Is with Ajax Request Cancel
After i call the ProcessMessage from form submit i am having issue
Issue with submitting your page is canceling my ajax request, so I am getting error..
Please help me on this
View
#using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "formUpload", enctype = "multipart/form-data" }))
{
<div>
<b>Upload File</b>
<input type="file" name="file" />
<input type="submit" value="Upload File" name="btnUpload" onclick="progressStatus();"/><br />
</div>
<div>
#ViewBag.Message
</div>
<div style="width: 30%; margin: 0 auto;">
<div id="progressbar" style="width: 300px; height: 15px"></div>
<br/>
</div>
}
#Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
function progressStatus() {
var oReq = new XMLHttpRequest();
oReq.open("get", "/Home/ProcessMessage", true);
oReq.send();
setInterval(showResult, 1000);
function showResult() {
var result = "";
if (result !== oReq.responseText) {
result = oReq.responseText;
debugger;
$("#progressbar").html(result);
}
}
return false;
}
</script>
Controller
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null)
{
var fname = Path.GetFileName(file.FileName);
var exis = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/Storage/uploads"), fname);
if (System.IO.File.Exists(exis))
{
ViewData["Message"] = "The file " + fname + " has already exists";
}
else
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var folderPath = Server.MapPath("~/Storage/uploads");
fname = fileName;
var path = Path.Combine(folderPath, fileName);
var filebytes = new byte[file.ContentLength];
if (!Directory.Exists(folderPath))
Directory.CreateDirectory(folderPath);
file.SaveAs(path);
}
ViewData["Message"] = "The file " + fname + " has uploaded successully";
}
catch (Exception e)
{
ViewData["Message"] = "The file " + fname + " Could not upload";
ViewData["Message"] = e.Message;
}
}
}
else
ViewData["Message"] = "Please choose file";
return View();
}
public class ProgressiveResult : ActionResult
{
public override void ExecuteResult(ControllerContext context)
{
for (int i = 0; i < 20; i++)
{
context.HttpContext.Response.Write(i.ToString());
Thread.Sleep(2000);
context.HttpContext.Response.Flush();
}
context.HttpContext.Response.End();
}
}
and this is an action that returns this result:
public ActionResult ProcessMessage()
{
return new ProgressiveResult();
}
You have to return false in click event handler to cancel submitting the form:
<input type="submit" value="Upload File" name="btnUpload" onclick="progressStatus(); return false;"/>

Categories

Resources