I need the c# code to upload images to my web api. (c# code that will do the same as my ajax call below)
Here is my working example that I use to upload images from my web project via ajax call.
HTML
<form>
<span>Select file(s) to upload :</span>
<input id="file1" name="file1" type="file" multiple="multiple" />
<input id="button1" type="button" value="Upload" />
</form>
ajax Call
$(document).ready(function () {
$("#button1").click(function (evt) {
var files = $("#file1").get(0).files;
if (files.length > 0) {
var data = new FormData();
for (i = 0; i < files.length; i++) {
data.append("file" + i, files[i]);
}
$.ajax({
type: "POST",
url: window.apiuri + "/api/book/UploadCover()",
contentType: false,
processData: false,
data: data,
success: function (messages) {
for (i = 0; i < messages.length; i++) {
$.smkAlert({ text: messages[i], type: 'success' });
}
},
error: function () {
$.smkAlert({ text: "Error while invoking the Web API", type: 'success' });
}
});
}
});
});
API Code in c#
public async Task<List<string>> UploadCover()
{
try
{
List<string> messages = new List<string>();
if (Request.Content.IsMimeMultipartContent())
{
string path = string.Format(#"C:\");
API.Classes.ImageUploads.MyStreamProvider streamProvider = new API.Classes.ImageUploads.MyStreamProvider(path);
await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (var file in streamProvider.FileData)
{
FileInfo fi = new FileInfo(file.LocalFileName);
try
{
messages.Add("<b>Book Cover Uploaded</b>");
}
catch (Exception ex)
{
messages.Add("<b>Upload Failed</b>");
}
}
return messages;
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
throw new HttpResponseException(response);
}
}
catch (Exception ex)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Request Failed!");
throw new HttpResponseException(response);
}
}
Please help me with c# code to upload images to my web api. Thank you
Related
I'm uploading an excel file and want to read file content and with jquery ajax fill some textboxes with excel content after uploading.
the file uploading correctly but I have Problem when I want read excel content.
can anybody help me?
public JsonResult ImportExcelToTextBoxes()
{
try
{
var ExcelFile = Request.Files[0];
if (ExcelFile != null && ExcelFile.ContentLength > 0)
{
//// .xlsx
//IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(ExcelFile.InputStream);
// .xls
IExcelDataReader reader = ExcelReaderFactory.CreateBinaryReader(ExcelFile.InputStream);
var result = reader.AsDataSet(new ExcelDataSetConfiguration() {
ConfigureDataTable = (_) => new ExcelDataTableConfiguration() {
UseHeaderRow = true
}
});
}
//foreach (var item in ExcelFile)
{
IList lst = new List<ET.Reservation.Classes.PassengerSaleSeat>();
ET.Reservation.Classes.PassengerSaleSeat pass = new ET.Reservation.Classes.PassengerSaleSeat();
pass.FirstName = "testtt";//this section is for test
pass.LastName = "tttttt";//this section is for test
pass.Gender = ET.Public.Enumerations.GENDER.Female;//this section is for test
lst.Add(pass);//this section is for test
}
return Json(lst);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw ex;
}
return null;
}
and js section:
$('#btnUploadExcel').click(function () {
var formData = new FormData();
formData.append('file', fileInput.files[0]);
$.ajax({
type: "POST",
url: "/PassengerSaleSeat/ImportExcelToDatabase",
data: formData,
processData: false,
contentType: false,
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].FirstName);
}
},
error: function(err) {
alert('error');
}
});
});
and input is:
<input id="fileInput" type="file">
<button type="button" id="btnUploadExcel" class="btn btn-labeled btn btn-success">Send</button>
JSON Return:
image
I'm trying to make use of the answer provided here:
Upload File Using WebAPI Ajax
But I keep receiving a 400 (Bad Request) error.
I've been submitting a pdf file but I keep receiving this error...
What am I doing wrong?
(FYI I'm not using MVC)
My code:
CSHTML (using Razor Syntax)
#{
Layout = "~/_SiteLayout.cshtml";
}
<label>Enter File</label>
<input type="file" name="UploadFile" id="datasheet_uploadfile" class="" accept="application/pdf"/>
<script>
$(document).ready(function() {
$('#datasheet_uploadfile').change(function() {
var data = new FormData();
var file = this.files;
data.append('file', file);
$.ajax({
url: '/api/file',
processData: false,
contentType: false,
data: data,
type: 'POST'
}).done(function(result) {
alert(result);
}).fail(function(a, b, c) {
console.log(a, b, c);
});
});
});
</script>
My WebAPI Controller
FileController.cs
public class FileController : ApiController
{
// POST api/<controller>
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
int hasheddate = DateTime.Now.GetHashCode();
//Good to use an updated name always, since many can use the same file name to upload.
string changed_name = hasheddate.ToString() + "_" + postedFile.FileName;
var filePath = HttpContext.Current.Server.MapPath("~/Content/stuff/" + changed_name);
postedFile.SaveAs(filePath); // save the file to a folder "Images" in the root of your app
changed_name = #"~\Content\stuff\" + changed_name; //store this complete path to database
docfiles.Add(changed_name);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
}
Use the below code to upload files
$(document).ready(function () {
$('#datasheet_uploadfile').change(function () {
var data = new FormData();
data.append("file", this.files[0]);
I'm doing a simple c# generic handler that should receive a form post. Here's the form...
<form id="frmUploadImage" action="../Handlers/LocalImageUploadHandler.ashx" method="post" style="display: none">
<div>
<input style="display: none; margin-bottom: 20px" type="file" id="uploadImage" />
</div>
</form>
I have some code that, upon the click of a button invokes the click event of the input. When the input is loaded, the following is invoked (I can set a breakpoint and it gets here).
var jqxhr = $.post('../Handlers/LocalImageUploadHandler.ashx', $('#frmUploadImage').serialize())
.success(function() {
alert('worked');
})
.error(function() {
alert('failed');
});
It will show an alert for "failed". Server-side, it is calling this in the handler (I can verify that it is getting invoked by setting a breakpoint).
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/octet-stream";
var file = Convert.FromBase64String(context.Request.Form["uploadedFile"]);
//other stuff
}
What's interesting is that the context.Request.Form and context.Request.Files properties have no items in them, even though they are being sent. Nothing I've done has worked. I've tried posting with XHR, jQuery, etc. I've tried pulling the data out of the file upload control as a DataUrl and serializing it to a base64 encoded string and putting it in an ajax call. The handler will receive a post, but the data is being stripped.
You need to tryout following code to make it working
User Side Code
$('#btnUpload').click(function () {
var fileUpload = $("#FileUpload1").get(0);
var files = fileUpload.files;
var test = new FormData();
for (var i = 0; i < files.length; i++) {
test.append(files[i].name, files[i]);
}
$.ajax({
url: "LocalImageUploadHandler.ashx",
type: "POST",
contentType: false,
processData: false,
data: test,
// dataType: "json",
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
});
Server Side Code
public void ProcessRequest (HttpContext context) {
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
fname=Path.Combine(context.Server.MapPath("~/uploads/"), fname);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
public bool IsReusable {
get {
return false;
}
}
I referred some Stack overflow Questions and I tried the following code. The following code was not hitting the Web API. I tried with normal Text, then its hitting but not for the FILE. Finally I concluded the Web API Path and method all are fine, only issue is File. Kindly assist me how to upload File using AngularJS to .NET Web API.
My HTML Code
<input id="file_input_file" ng-files="getTheFiles($files)" type="file" accept=".csv" />
<input type="button" data-ng-click="ImplortCSVData()" id="btnMainLoginForm" value="Upload File" />
My AngularJS Directive for ng-files is
app.directive('ngFiles', ['$parse', function ($parse) {
function fn_link(scope, element, attrs) {
var onChange = $parse(attrs.ngFiles);
element.on('change', function (event) {
onChange(scope, { $files: event.target.files });
});
};
return {
link: fn_link
}
}]);
My AnagularJS Controller is
app.controller('ProcessCSVController', function ($rootScope, $scope, HTTPService) {
$scope.CSVfile = {};
$scope.getTheFiles = function ($files) {
angular.forEach($files, function (value, key) {
$scope.CSVfile.append(key, value);
});
};
$scope.ImplortCSVData = function () {
HTTPService.uploadCSV($scope.CSVfile).then(function (result) {
alert("CSV");
});
}
});
My HTTPService is
app.factory('HTTPService', function ($http, $q) {
formatCSV: function (_resultObj) {
var result = $http({
url: "localhost:8085/api/TAdmin/UploadCSVData",
method: 'POST',
data: _resultObj,
headers: {
"Content-Type": undefined
},
}).success(function (response) {
return {
errorCode: 0,
errorString: "",
result: response
}
}).error(function (error) {
return {
errorCode: 100,
errorString: "",
result: error
}
});
return result;
}
});
My WebAPI C# Code is
[HttpPost]
public HttpResponseMessage UploadCSVData(object csv)
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
BinaryFormatter bf = new BinaryFormatter();
using (var ms = new MemoryStream())
{
bf.Serialize(ms, csv);
var x = ms.ToArray();
}
return Request.CreateResponse(HttpStatusCode.OK);
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
This form i want to send using ajax call with file, but it is not calling the c# function and not showing any error.
//form to submit
<form id="formfile" enctype="multipart/form-data">
<div class="modal-body">
<input type="file" id="fileupload1"/>
</div>
<div class="modal-footer">
<input type="submit" id="savefiles" class="buttonType" onclick="saveFile();return false" value="Save File" />
</div>
</form>
This ajax call is used to call c# code and also send file(.pdf)
//ajax call in .aspx file
function saveFile() {
debugger;
var file = $('input[type="file"]').val();
var exts = ['pdf', 'PDF'];
var formData = new FormData();
formData.append("imageFile", $('#fileupload1')[0].files[0]);
if (file) {
var extension = file.substring(file.lastIndexOf('.') + 1, file.length);
if ($.inArray(extension, exts) > -1)
{
//var formData = new FormData($('#form1')[0]);
var fileUpload = $('#fileupload1').get(0);
var files = fileUpload.files;
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
formData.append(fileUpload.name, fileUpload);
//alert('File Uploaded Successfully!');
}
else
{
alert('Invalid file, Only pdf files can be uploaded!!!');
}
}
//var str = "abc";
$.ajax({
url: "FileUploader.aspx/savepdfFiles",
type: "POST",
//cache: false,
contentType: false,
processData: false,
data: formData,
success: function (data) {
debugger;
},
error: function (data) {
debugger
}
});
}
It will come into success section also, but not calling following method.
//c# code
[webMethod]
public static void savepdfFiles()
{
//code
}
In ajax call it goes into success. but not calling savepdfFiles() method.
EDIT 24/08/2016
You can convert your blob data to base 64 and send it in JSON
var filesLength = 0;
function SaveFileToTemp() {
var file = $('input[type="file"]').val();
var exts = ['pdf', 'PDF'];
var pdfList = [];
// var pdfFile = { FileName: '', B64Data: '' };
if (file) {
var extension = file.substring(file.lastIndexOf('.') + 1, file.length);
if ($.inArray(extension, exts) > -1) {
var fileUpload = $('#fileupload1').get(0);
var files = fileUpload.files;
filesLength = files.length;
for (var i = 0; i < files.length; i++) {
var reader = new window.FileReader();
reader.myFileIndex = i;
reader.onloadend = function () {
base64data = reader.result;
pdfList.push({ FileName: files[this.myFileIndex].name, B64Data: base64data.substr(base64data.indexOf(',') + 1) });
console.log(base64data);
filesLength--;
if (filesLength === 0) {
$.ajax({
url: "/FileUploader.aspx/savepdfFiles",
type: "POST",
//cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ listPdf: pdfList }),
success: function (data) {
//alert('File Uploaded Successfully!');
debugger;
},
error: function (data) {
debugger
}
});
}
}
reader.readAsDataURL(files[i]);
}
}
else {
alert('Invalid file, Only pdf files can be uploaded!!!');
}
}
}
and in C#
[WebMethod]
public static void savepdfFiles(List<PdfFile> listPdf)
{
//code
foreach (var item in listPdf)
{
byte[] data = Convert.FromBase64String(item.B64Data);
System.IO.File.WriteAllBytes(string.Format("d:\\temp\\{0}",item.FileName), data) ;
}
}
this is my clas PdfFile for info
public class PdfFile
{
public string FileName { get; set; }
public string B64Data { get; set; }
}
Maybe you have to add this to your web.config to allow big json serialization :
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="10240000"/>
</webServices>
</scripting>
</system.web.extensions>
You have to set the appropiate value for maxJsonLength
Previous answer
I think I had this problem before from what i remember there is mechanism that doesn't allow you to this.
Maybe I'm wrong but I share you a link.
You will have to handle this with an ashx.
here is a built-in validation layer of protection that ASP.NET
enforces for both GET and POST based ASP.NET AJAX web methods, which
is that regardless of the HTTP verb being used, ASP.NET always
requires that the HTTP Content-Type header is set to the value
application/json. It this content type header is not sent, ASP.NET
AJAX will reject the request on the server.
I know this problem and it's easy to solve just you have to use Generic Handler.
Using generic handler with your AJAX call you can send any file to asp.net C# function.
In Generic Handler you have to write following c# code.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
namespace UploadFile
{
/// <summary>
/// Summary description for UploadFileHandler
/// </summary>
public class UploadFileHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
//context.Response.ContentType = "text/plain";
//context.Response.Write("Hello World");
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE" || HttpContext.Current.Request.Browser.Browser.ToUpper() == "INTERNETEXPLORER")
{
string[] testfiles = file.FileName.Split(new char[] { '\\' });
fname = testfiles[testfiles.Length - 1];
}
else
{
fname = file.FileName;
}
fname = Path.Combine(context.Server.MapPath("~/Uploads/"), fname);
file.SaveAs(fname);
}
}
context.Response.ContentType = "text/plain";
context.Response.Write("File Uploaded Successfully!");
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
Here is the example...
If you want Full Example Click here!