Angular 2 save Excel File - asp.net

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());
}

Related

Response of Requests made shown as empty in json report of newman

After running the collection using newman with json reporter, json file gets generated.
But for response portion it is [] i.e. empty, while it has different response related attributes with proper values (e.g. for responseTime, responseSize, etc).
So how can I get the response body/data in this json reporter.
As per my actual requirement, I need to record response for each request made in either json or excel/csv format file.
While I was not able to solve this problem directly, I used Newman as a javascript library and recorded the request and response in separate text files.
The files generated will have file names like request1, request2 and so on for request files; and similar behavior will be for response files and their names for every execution.
Below is the code for the above mentioned solution:
const newman = require('newman'),
fs = require('fs');
var rq = 1;
var rs = 1;
newman.run({
collection: require('./ABC.postman_collection.json'),
environment: require('./XYZ.postman_environment.json'),
iterationData: './DataSet.csv',
reporters: 'cli'
}).on('beforeRequest', function (error, args) {
if (error) {
console.error(error);
} else {
fs.writeFile('request' + rq++ + '.txt', args.request.body.raw, function (error) {
if (error) {
console.error(error);
}
});
}
}).on('request', function (error, args) {
if (error) {
console.error(error);
}
else {
fs.writeFile('response' + rs++ + '.txt', args.response.stream, function (error) {
if (error) {
console.error(error);
}
});
}
});

Uploaded File not showing in asp.net web api controller

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]

ASP.NET return null or no connection from angular4

I am trying to send JSON string from angular to asp.net server. I tried two things to get this data from client side.
1st : I have following code from both server and client side. I am sending a json string, and I expected to receive at backend for what I sent. However, I am just getting this server error before even getting the data.
POST "url" 404 (not found)
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:61476/api/testAPI/getData'.","MessageDetail":"No action was found on the controller 'getData' that matches the request."}
2nd : given that everything is same, i just added [FromBody] in my method like below. This doesn't return any server error and I am able to connect from my client side to server. However, I am getting my body message as null . I tried with Postman, but it seems that it works fine with Postman when I send same data.. I am aware that I can create some modelling in server code to match with my json string from client side, but I don't get why this doesn't work without modelling and also why connection fails without [FromBody].
All I need is to get JSON string from my client side. Can anyone please provide me advice on this?
public string getData([FromBody] string body)
angular
callServer(){
var json = {"name":"John Doe", "school": "A"};
let headers = new HttpHeaders();
headers.set('Content-Type', 'application/json');
this.appService.http.post('http://localhost:61476/api/testAPI/getData',
json,
{headers: headers})
.subscribe(data => {console.log(data), (err) => console.error("Failed! " + err);
})
}
server
namespace test.Controllers
{
public class testAPIController : ApiController
{
//
[HttpPost]
public string getData(string body)
{
try
{
Log.Info(string.Format("data {0}", body));
return "ok";
}
catch (Exception ex)
{
Log.Error(ex.Message);
return "error";
}
}
}}
Controller:
[HttpPost]
public string postData([FromBody]string body)
{
try
{
Log.Info(string.Format("data {0}", body));
return Json("ok");
}
catch (Exception ex)
{
Log.Error(ex.Message);
return "error";
}
}
Calling the server:
callServer() : Observable<string> {
var json = {"name":"John Doe", "school": "A"};
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let apiUrl = 'http://localhost:61476/api/testAPI/postData';
return this.appService.http.post(`${this.apiUrl}`, json, options)
.map((res: Response) => res.json())
.catch(this.handleErrorObservable);
}
private handleErrorObservable(error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
Calling the service:
this._service.callServer()
.subscribe(
res => { console.log(res) },
err => { console.log(err) }
)
console.log(res/err) will be your response from the POST call. Sorry if misinterpreted your question but your question is a little hard to follow.
404 error is "not found". You must decorate your API Class
[Route("api/TestApi/[action]")]
public class testAPIController : ApiController
{
[HttpPost]
[HttpPost, ActionName("getData")]
public string getData([FromBody]string body)
{}
}

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);
}

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