Uploaded File not showing in asp.net web api controller - asp.net

I am trying to build simple image upload program and it's not working
my code as follows . if anyone can figure this out it will be life saving for me
thanks
here is my angular service
postFiles(caption: string, filetouplaod: File) {
const headerss = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': this.globalsr.PrimaryTocken
})
let file: File = filetouplaod;
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
return this._http.post(`${this.globalsr.PrimaryAPI}Uploader/UploadSingleImage`, formData, {headers:headerss})
}
Auth token
private _primaryTocken: string = "Bearer ansKFMPonKyab-TBmgQAThXNKoSAt8ZHej31-Is1a0X0wo5iSIjiaXvRdHscyr9J3v3iG3PTg8_BnoZaiMRCEY03zAONYrKppp1ZdSAgGenMcqeW-UYyKKkOEk7UhXO3l1_-9kXc9rBnekuOIqCrH8TfbcF_G_hgUVFS2N8omQYetJ-VobtaW8n-8AZL72wigGeckLtjZhm12aEEwxsDxnrrY4WA0kB3T9eNURvSO_9lwjJ2_oBRwOPojcAh-dfrlOln0DkSpYL8F2Si2Od63pesFnMZ9uhBkYjZvWCfeN0k8-V7jvBLae_Pz_ljoYM1rVRF-CXwQgBOKiKmSi9h65DUAsqaQY8gLXb69xqPmomscXLn4yVwsdkNyZlayuVlL3EhQgjslgss6xqiUw36SPSsfTN9rMmRQr3dpiJogn61U7kF5FqCRAhmjj_JPOo8aXoh1EGkov0ArerB6lgMDvt3UM_f8-Dzi0i8vtZrstg" ;
My Web api Controller
[Authorize]
[HttpPost]
[Route("UploadSingleImage")]
public HttpResponseMessage UploadSingleImage()
{
var exMessage = string.Empty;
try
{
string uploadPath = "~/content/upload";
HttpPostedFile file = null;
if (HttpContext.Current.Request.Files.Count > 0)
{
file = HttpContext.Current.Request.Files.Get("file");
}
// Check if we have a file
if (null == file)
return Request.CreateResponse(HttpStatusCode.BadRequest, new
{
error = true,
message = "Image file not found"
});
// Make sure the file has content
if (!(file.ContentLength > 0))
return Request.CreateResponse(HttpStatusCode.BadRequest, new
{
error = true,
message = "Image file not found"
});
if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadPath)))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadPath));
}
//Upload File
file.SaveAs(HttpContext.Current.Server.MapPath($"{uploadPath}/{file.FileName}"));
}
catch (Exception ex)
{
exMessage = ex.Message;
}
return Request.CreateResponse(HttpStatusCode.BadRequest, new { error = true, message = exMessage == string.Empty ? "An unknown error occured" : exMessage });
}
but the case is this file count is zero all the time.
HttpContext.Current.Request.Files.Count
so I've send the exact data using postman and web api method works fine.
any ideas please

Don't set 'Content-Type': 'multipart/form-data' - just remove it.
Generaly after it I removed Content-Type in all my requests and replaced it by 'Accept': 'application/json'.

file is not able to get the file you are trying to upload from file input element. Use cosole log to check contents of filetouplaod.
let file: File = filetouplaod;
Lets say fileInput is the input element, then you should assign something like this filetouplaod = fileInput.files[0]

Related

Angular 2 save Excel File

I'm trying to save a Excel File from my server to Client PC but it get all messed up.
When I request my file to the server the body of the request comes like this:
��ࡱ�>�� &����
I guess it's normal since excel is in binary format. I'm using file-saver plugin to save my files, at the moment I have the CSV and ASCII files working well.
This is my function to download:
downloadFile(filePath: string, name: string): void{
this.dataImportService.downloadFile(filePath)
.then(data => {
this.headers = data.headers;
let content = this.headers.get('content-type');
var blob = new Blob([data._body], { type: content });
importedSaveAs(blob, name);
});
}
Anything that I'm doing wrong or that I can improve?
Thank you in advance for the help.
EDIT: This is my server code:
[HttpGet]
public void downloadFile(string path)
{
try
{
string extension = Path.GetExtension(path);
string fileName = Path.GetFileName(path);
HttpResponse response = System.Web.HttpContext.Current.Response;
response.AppendHeader("Content-Disposition", "attachment; filename="+fileName);
response.AddHeader("Content-Type", Utils.MimeTypesConverter.GetMimeType(extension));
response.TransmitFile(path);
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.Message);
return;
}
}
and my dataImportService.ts
downloadFile(filePath: string): any{
return this.http.get(SERVICE_URL + 'DataImport/downloadFile?path=' + filePath)
.toPromise()
.then(response =>{
return response;
})
.catch(this.handleError);
}
My http response from server:
You have to map the Response which includes HTTP Headers to the Blob on it's own.
So change code to an Observable wtih a map to transform response.
downloadFile(filePath: string): Observable<any> {
return this.http.get(
`${SERVICE_URL}DataImport/downloadFile?path=${filePath}`,
{responseType: ResponseContentType.Blob }
)
.map(res:Response => res.blob());
}

Ionic XMLHttpRequest FormData empty after append file

I'm trying to send a file with a post with ionic 2
In order to ask for the file, i use an invisible input type file
<input type="file" accept="image/*;" #file id="fileUpoload" style="display: none">
The button call the function in this way:
(click)="onFileUpoloadButtonPressed(file)"
And this is the function called:
onFileUpoloadButtonPressed(element){
document.getElementById("fileUpoload").onchange = function(e : any){
let file = {
name: e.srcElement.files[0].name,
file: e.srcElement.files[0],
};
//I get the id of the user since i have to perform an edit call to my api
this.storage.get("userLogged").then((value) => {
setTimeout(function(){
this.postChangeAvatar(this, parseInt(value.data.utenti_id), file,
function (ext, result){ //Success callback
console.log(result);
},
function(ext, error){ //Error callback
console.log(error);
alert(error);
}
)
}, 100)
})
}
element.click();
}
This is the postChangeAvatar function that perform the post request:
postChangeAvatar(ext, id, file, successCallback, errorCallback){
let formData : any = new FormData();
let xhr : any = new XMLHttpRequest();
console.log(id);
console.log(file); //File is successfully get
formData.append('user_photo', file.file, file.name);
for (var pair of formData.entries()) { //This is showing nothing
console.log(pair[0]+ ', ' + pair[1]);
}
xhr.onreadystatechange = () => {
if (xhr.readyState == 4){
if (xhr.status == 200){
successCallback(ext, xhr.response);
}
else {
errorCallback(ext, xhr.response);
}
}
}
xhr.open('POST', "http://xxxxxxxxxx/api/edit/utenti/" + id, true);
xhr.send(formData);
}
The post is performed but the formData remains empty after append the file, trying to print the formdata with the for each doesn't show anything, so the only thing wrong is the formData being empty when post is performed
As you can see i tried to encapsulate the entire request in a setTimeout to be sure the file is obtained, the file is in there but is not appendend in the formData
From the server i can see the body of the request empty
I tried this method in another project and in there was successfully working so i'm a bit surprised seeing this not working
If i'm not able to get this working maybe there's another way to post selected files with ionic 2?
Here is working piece of code (base64 file upload). Try setting header. Add enctype to Access-Control-Expose-Headers to prevent CORS.
insertPost(data): Observable<any> {
let headers = new Headers({ "enctype": "multipart/form-data" });
data.userId = this.globalProvider.userId;
var form_data = new FormData();
for (var key in data) {
form_data.append(key, data[key]);
}
return this.http.post(`${baseURL}insertPost`, form_data, { headers: headers })
.map((response: Response) => {
return response.json();
})
.catch(this.handleError);
}

Can't send data with $http.post in Ionic Framework

I'm trying make an application with Ionic framework which can take and send data to MS SQL server. For this I am using web api. I have no problem with taking data but something wrong with send new datas. Here is my ionic code :
angular.module('starter.controllers',[])
.controller('CheckListCtrl', function($scope, ChecklistService, $ionicPopup) {
function addCheck(){
ChecklistService.addCheck()
}
.factory('ChecklistService', ['$http', function ($scope, $http) {
var urlBase = 'http://localhost:56401/api';
var CityService = {};
CityService.addCheck = function(){
var url = urlBase + "/TBLCHECKLISTs"
var checkdata = {
AKTIF : true,
SIL : false,
KAYITTARIHI : Date.now(),
KULLANICIID : 3,
BASLIK : "Onur",
TAMAMLANDI : false,
TAMAMLANMATARIHI : null,
GUN : 1
}
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: checkdata
});
return request;
}
return CityService;
}]);
And here is my web api:
[HttpPost]
[ResponseType(typeof(TBLCHECKLIST))]
public IHttpActionResult PostTBLCHECKLIST(TBLCHECKLIST tBLCHECKLIST)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
tBLCHECKLIST.KAYITTARIHI = DateTime.Now;
db.TBLCHECKLISTs.Add(tBLCHECKLIST);
db.SaveChanges();
return CreatedAtRoute("DefaultApi", new { id = tBLCHECKLIST.TABLEID }, tBLCHECKLIST);
}
When i try to send i get this exception:
After, I realize that I take that exception because my checkdata is never come to web api. I don't know why.
These are not the datas I send:
I have tried different versions of post request but nothing. When I try to send data with PostMan, it works and I can insert data to my database. But why I can't do it with my application? Can anybody help me?
I think this should be the problem:
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
Try this:
return $http.post(url, checkdata);
And in your API:
[HttpPost]
[ResponseType(typeof(TBLCHECKLIST))]
public IHttpActionResult PostTBLCHECKLIST([FromBody]TBLCHECKLIST tBLCHECKLIST)
{
//code here
}
Also, make sure your checkdata properties match the ones in your TBLCHECKLIST c# type.

Save a Excel File From API controller in AngularJS

I have tried to download a file from a method of my Web API Controller (Asp.net MVC 6). So, my file is created in a api controller and I want download my file, already in excel format, with angularjs. But, I don't know how to do.
Here is my method in my api controller: (it works, I already use this methods and class in an another project Asp.net without angularj)
#region downloadFile
[Route("Download")]
public ActionResult Download()
{
string companyName = Context.Session.GetString("companyName") as string;
string fileDownloadName = Context.Session.GetString("fileDownloadName") as string;
string baseFolder = System.IO.Path.Combine("C:\\Temp");
string folder = System.IO.Path.Combine(baseFolder, companyName);
TempFile tempFile = new TempFile(folder, fileDownloadName);
tempFile.FindFileInDirectory();
return File(tempFile._pathDirectory + "\\"+tempFile._fileName, "Application/" + tempFile._fileExt, tempFile._fileName);
}
#endregion
This method returns an excel file. Now, I would download this file that is send in angularjs with a http request.
I have tried to use the method saveAs from fileSaver.js. I have added the js in my project but when I want use it, the method is always undefined.
var requestDownloadFile =
$http({
url: '/api/customers/Download'
, responseType: 'arraybuffer'
, headers: {
'contentType': 'application/json'
, 'Accept': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
}
});
requestDownloadFile.success(function (data) {
saveAs(data, 'test.xlsx');
});
I tried to use this too in my success method:
var blob = new Blob([data], { type: "application/vnd.openxmlformats- officedocument.spreadsheetml.sheet" })
var objectUrl = URL.createObjectURL(blob);
window.open(objectUrl);
It run a download file, but the file is corrupted.
So it's not realy effective because I have created a file in API and I have tried to recover an arrayBuffer but I'm blocked so I try.
All support is welcome. Thanks
So, I complicated life. I just had to do this in the success:
window.open('/api/customers/Download', '_blank', '');
window.open('link/to/method/api', '_blank', '');

problems with sending jpg over http - node.js

I'm trying to write a simple http web server, that (among other features), can send the client a requested file.
Sending a regular text file/html file works as a charm. The problem is with sending image files.
Here is a part of my code (after parsing the MIME TYPE, and including fs node.js module):
if (MIMEtype == "image") {
console.log('IMAGE');
fs.readFile(path, "binary", function(err,data) {
console.log("Sending to user: ");
console.log('read the file!');
response.body = data;
response.end();
});
} else {
fs.readFile(path, "utf8", function(err,data) {
response.body = data ;
response.end() ;
});
}
Why all I'm getting is a blank page, upon opening http://localhost:<serverPort>/test.jpg?
Here's a complete example on how to send an image with Node.js in the simplest possible way (my example is a gif file, but it can be used with other file/images types):
var http = require('http'),
fs = require('fs'),
util = require('util'),
file_path = __dirname + '/web.gif';
// the file is in the same folder with our app
// create server on port 4000
http.createServer(function(request, response) {
fs.stat(file_path, function(error, stat) {
var rs;
// We specify the content-type and the content-length headers
// important!
response.writeHead(200, {
'Content-Type' : 'image/gif',
'Content-Length' : stat.size
});
rs = fs.createReadStream(file_path);
// pump the file to the response
util.pump(rs, response, function(err) {
if(err) {
throw err;
}
});
});
}).listen(4000);
console.log('Listening on port 4000.');
UPDATE:
util.pump has been deprecated for a while now and you can just use streams to acomplish this:
fs.createReadStream(filePath).pipe(req);

Resources