my goal is to populate an array via for loop. and then send that array in HTTP POST call,
i.e: first upload all the files, then push each file details in array.
// For multiple files
for (let i = 0; i < projectRefFilesForUploading.length; i++) {
this.postSingleFile([] = projectRefFilesForUploading[i].file, projectDir).then(uploadedFiles => {
let filePath = uploadedFiles['projectRefFiles'][0].fd;
filePath = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."));
let filename = uploadedFiles['projectRefFiles'][0].filename;
let size = uploadedFiles['projectRefFiles'][0].size;
let type = uploadedFiles['projectRefFiles'][0].type;
let status = uploadedFiles['projectRefFiles'][0].status; // finished
let fileNote = projectRefFilesForUploading[i].fileNote;
projectRefFilesDataArray.push({fileName: filename, filePath: filePath, size: size, type: type, fileNote: fileNote});
});
}
i.e: now post the array in http post call.
let body = {
projectId: projectId,
projectRefFiles: projectRefFilesDataArray
}
let headers = new Headers();
let options: RequestOptionsArgs = { headers: headers, withCredentials: true }
return new Promise((resolve, reject) => {
this.http.post( this.apiEndpoint + "/add/all", body, options).toPromise()
.then(response => {
let jsonData = response.json();
if (jsonData.apiStatus == 1) {
resolve(jsonData);
}
else reject(jsonData.message);
})
.catch(reason => reject(reason.statusText));
});
the problem is due to async function calls, http call post its data in parallel to loop execution. so it sends an empty array in http call. if I put the call method inside the loop then it works. but it created too much http call along with looping.
please help me how to detect, loop finishes it execution then after http call
try this :
let promise = new Promise((resolve, reject) => {
let count = 0;
for (let i = 0; i < projectRefFilesForUploading.length; i++) {
this.postSingleFile([] = projectRefFilesForUploading[i].file, projectDir).then(uploadedFiles => {
count++;
let filePath = uploadedFiles['projectRefFiles'][0].fd;
filePath = filePath.substring(filePath.lastIndexOf("/") + 1, filePath.lastIndexOf("."));
let filename = uploadedFiles['projectRefFiles'][0].filename;
let size = uploadedFiles['projectRefFiles'][0].size;
let type = uploadedFiles['projectRefFiles'][0].type;
let status = uploadedFiles['projectRefFiles'][0].status; // finished
let fileNote = projectRefFilesForUploading[i].fileNote;
projectRefFilesDataArray.push({fileName: filename, filePath: filePath, size: size, type: type, fileNote: fileNote});
if(count === projectRefFilesForUploading.length){
resolve(projectRefFilesForUploading);
}
});
}
});
promise.then(function(projectRefFilesDataArray){
let body = {
projectId: projectId,
projectRefFiles: projectRefFilesDataArray
}
let headers = new Headers();
let options: RequestOptionsArgs = { headers: headers, withCredentials: true }
return new Promise((resolve, reject) => {
this.http.post( this.apiEndpoint + "/add/all", body, options).toPromise()
.then(response => {
let jsonData = response.json();
if (jsonData.apiStatus == 1) {
resolve(jsonData);
}
else reject(jsonData.message);
})
.catch(reason => reject(reason.statusText));
});
});
Related
I am trying to post a random dog picture when someone says toggledoggo. Every time I try to run the command, it gives me an error message in the terminal, and does nothing.
Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", message => {
var prefix = 'toggle';
var doggos = ['dog1', 'dog2'];
var dog1 = message.channel.send({ files: ['dog1.jpg'] });
var dog2 = message.channel.send({ files: ['dog2.jpg'] });
if (message.content.startsWith(prefix + 'doggo')) {
Math.floor(Math.random() * doggos.length);
};
});
client.login('token');
If you want a truly random picture (pseudo-random but still) use an api. I use dog.ceo. Heres a code that, while big, gives a user plenty of options to choose from.
if(msg.split(' ')[0] === prefix + "doggo"){
let breeds = []; // Initializing an array to use later
let breeds2 = []; // Due to the size, we need to split it.
request('https://dog.ceo/api/breeds/list/all', async function (error, response, body) { // Begin a request to list all breeds.
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
for(var name in importedJSON.message){ // looping through every breed and pushing it into the array made earlier
breeds.push(name)
if(importedJSON.message[name].length != 0){
for(var i = 0; i < importedJSON.message[name].length; i++){
breeds.push("- " + importedJSON.message[name][i]) // Pushing sub-breeds into the array too
}
}
}
for(var j = 0; j < breeds.length/2; j++){ // Halving the previous array because it's too big for one message.
let toArray = breeds.shift()
breeds2.push(toArray)
}
}
})
let args = msg.split(' ').slice(1)
if(!args[0]){ // if no breed, then send a random image
request('https://dog.ceo/api/breeds/image/random', async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}
})
}
if(args[0] === "breeds"){ // Command to list the breeds.
setTimeout(async function(){
let m = breeds2.map(name => name.charAt(0).toUpperCase() + name.slice(1)) // Creating a map of the arrays earlier to send as a message
let m2 = breeds.map(name => name.charAt(0).toUpperCase() + name.slice(1))
await message.channel.send(m)
return await message.channel.send(m2)
}, 1000);
}
if(args[0]){
setTimeout(async function(){
for(var i = 0; i < breeds.length; i++){ // Looping through every breed in the array to see if it matches the input
if(args[0] == breeds[i]){
let input = breeds[i]
args.shift() // This is to check for a sub breed input, which is taken into account in the else statement of this if statement
if(!args[0] || args[0] == undefined){
request(`https://dog.ceo/api/breed/${input}/images/random`, async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}else{
request(`https://dog.ceo/api/breed/${input}/${args[0]}/images/random`, async function (error, response, body) { // requesting a dog of a certain breed and sub breed
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}
}
}
for(var i = 0; i < breeds2.length; i++){ // This is identical to the above, but with the other array
if(args[0] == breeds2[i]){
let input = breeds2[i]
args.shift()
if(!args[0] || args[0] == undefined){
request(`https://dog.ceo/api/breed/${input}/images/random`, async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}else{
request(`https://dog.ceo/api/breed/${input}/${args[0]}/images/random`, async function (error, response, body) {
if (!error && response.statusCode == 200) {
var importedJSON = JSON.parse(body);
return await message.channel.send(importedJSON.message)
}else{
await message.channel.send(`You must have typed something wrong, do ${prefix}doggo breeds for a list of breeds.`)
return
}
})
return
}
}
}
}, 1000);
}
};
The acceptable command for this are: (prefix)doggo, (prefix)doggo breeds, (prefix)doggo (breed), (prefix)doggo (breed) (sub breed)
You will need the "request" module you can read up on it here: https://www.npmjs.com/package/request. Hopefully the comments I put in the code are enough to explain whats going on if not, ask for clarification. If you just wanted a small command for 2 pictures then you can also tell me and I'll delete this post entirely.
I had to do three HTTP Post requests in my code. The first two work, I debug the code and they return the correct value, but the last one returns undefined.
I made these three requisitions due to one depending on the response of the other.
login button:
goToMenu() {
this.dados_login = [];
this.dados_login.push({
"CPF": this.cpfLogin,
"Senha": this.senhaLogin
})
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
let options = new RequestOptions({ headers: headers });
return new Promise((resolve, reject) => {
this.http.post(this.url, JSON.stringify(this.dados_login["0"]), options)
.toPromise()
.then((response) => {
var json_token = (response as any)._body;
var parsed = JSON.parse(json_token);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.token = arr[0];
this.carregaEmpresas();
})
.catch((error) => {
var json_error = (error as any)._body;
var parsed = JSON.parse(json_error);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.error_login = arr[0];
this.presentAlert(this.error_login)
});
});
function that carries companies, the error occurs here because it is not returned nothing to it
carregaEmpresas(newpage: boolean = false) {
console.log(this.cpfLogin);
this.abreCarregando();
return new Promise((resolve, reject) => {
this.EmpresaProvider.getEmpresas(this.token, this.cpfLogin)
.then((response) => {
var json_emp = (response as any)._body;
var parsed = JSON.parse(json_emp);
var arr_emp = [];
for (var x in parsed) {
arr_emp.push(parsed[x]);
}
this.lista_empresas = arr_emp;
this.objEmp = [];
for (let i = 0; i < this.lista_empresas.length; i++) {
this.obj = {
label:
this.lista_empresas[i].Valor,
type: 'radio',
value: this.lista_empresas[i].Chave
}
this.objEmp.push(this.obj);
}
this.fechaCarregando();
this.selectEmpresa();
})
.catch((error) => {
var json_error = (error as any)._body;
var parsed = JSON.parse(json_error);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.error_login = arr[0];
this.presentAlert(this.error_login)
});
});
provider role:
return new Promise((resolve, reject) => {
this.http.post(this.baseApiPath, JSON.stringify(this.cpf_usuario["0"]), options)
.toPromise()
.then((response) => {
var empresa = (response as any)._body;
var parsed = JSON.parse(empresa);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.empresa_cod = arr[0].Chave.split("/", 1);
var urlFilial = this.apiFilial + this.empresa_cod["0"];
return this.http.get(urlFilial, options);
})
.catch((error) => {
var json_error = (error as any)._body;
var parsed = JSON.parse(json_error);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
return arr[0];
});
});
GetEmpresas Code:
getEmpresas(token: string, Cpf: string) {
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
headers.append('Authorization', 'bearer ' + token);
let options = new RequestOptions({ headers: headers });
this.cpf_usuario.push({ "Cpf": Cpf });
return new Promise(resolve => {
window.setTimeout(() => {
this.http.post(this.baseApiPath, JSON.stringify(this.cpf_usuario["0"]), options)
.toPromise()
.then((response) => {
var empresa = (response as any)._body;
var parsed = JSON.parse(empresa);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.empresa_cod = arr[0].Chave.split("/", 1);
var urlFilial = this.apiFilial + this.empresa_cod["0"];
return this.http.get(urlFilial, options)
.toPromise()
.then((response) => {
var json_emp = (response as any)._body;
var parsed = JSON.parse(json_emp);
var arr_emp = [];
for (var x in parsed) {
arr_emp.push(parsed[x]);
}
this.emp = arr_emp;
return arr_emp;
})
})
.catch((error) => {
var json_error = (error as any)._body;
var parsed = JSON.parse(json_error);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
return arr[0];
});
}, 2000);
});
}
This is a draft because I'm not sure I've found the problem yet, but I need to share more code than will fit in a comment.
The first thing I would try is removing the new Promise because you aren't resolving or rejecting those promises anyway. I'd also try removing the window.setTimeout. At that point, it looks like getEmpresas will return a promise for the arr_emp that is the result of parsing the final get response. If you do that, then the then handler in carregaEmpresas will receive the arr_emp that was generated in getEmpresas, so you should just name the parameter arr_emp and not try to parse it again. The code at this point is:
class MyClass {
// Dummy declarations to suppress TypeScript errors
dados_login;
cpfLogin;
senhaLogin;
http;
url;
token;
error_login;
presentAlert;
abreCarregando;
lista_empresas;
objEmp;
obj;
fechaCarregando;
selectEmpresa;
EmpresaProvider: EmpresaProvider;
goToMenu() {
this.dados_login = [];
this.dados_login.push({
"CPF": this.cpfLogin,
"Senha": this.senhaLogin
})
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
let options = new RequestOptions({ headers: headers });
this.http.post(this.url, JSON.stringify(this.dados_login["0"]), options)
.toPromise()
.then((response) => {
var json_token = (response as any)._body;
var parsed = JSON.parse(json_token);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.token = arr[0];
this.carregaEmpresas();
})
.catch((error) => {
var json_error = (error as any)._body;
var parsed = JSON.parse(json_error);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.error_login = arr[0];
this.presentAlert(this.error_login)
});
}
carregaEmpresas(newpage: boolean = false) {
console.log(this.cpfLogin);
this.abreCarregando();
this.EmpresaProvider.getEmpresas(this.token, this.cpfLogin)
.then((/*response*/ arr_emp) => {
/*
var json_emp = (response as any)._body;
var parsed = JSON.parse(json_emp);
var arr_emp = [];
for (var x in parsed) {
arr_emp.push(parsed[x]);
}
*/
this.lista_empresas = arr_emp;
this.objEmp = [];
for (let i = 0; i < this.lista_empresas.length; i++) {
this.obj = {
label:
this.lista_empresas[i].Valor,
type: 'radio',
value: this.lista_empresas[i].Chave
}
this.objEmp.push(this.obj);
}
this.fechaCarregando();
this.selectEmpresa();
})
.catch((error) => {
var json_error = (error as any)._body;
var parsed = JSON.parse(json_error);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.error_login = arr[0];
this.presentAlert(this.error_login)
});
}
}
class EmpresaProvider {
// Dummy declarations to suppress TypeScript errors
cpf_usuario;
http;
baseApiPath;
empresa_cod;
apiFilial;
emp;
getEmpresas(token: string, Cpf: string) {
let headers = new Headers();
headers.append('Content-Type', 'application/json; charset=UTF-8');
headers.append('Authorization', 'bearer ' + token);
let options = new RequestOptions({ headers: headers });
this.cpf_usuario.push({ "Cpf": Cpf });
return this.http.post(this.baseApiPath, JSON.stringify(this.cpf_usuario["0"]), options)
.toPromise()
.then((response) => {
var empresa = (response as any)._body;
var parsed = JSON.parse(empresa);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
this.empresa_cod = arr[0].Chave.split("/", 1);
var urlFilial = this.apiFilial + this.empresa_cod["0"];
return this.http.get(urlFilial, options)
.toPromise()
.then((response) => {
var json_emp = (response as any)._body;
var parsed = JSON.parse(json_emp);
var arr_emp = [];
for (var x in parsed) {
arr_emp.push(parsed[x]);
}
this.emp = arr_emp;
return arr_emp;
})
})
.catch((error) => {
var json_error = (error as any)._body;
var parsed = JSON.parse(json_error);
var arr = [];
for (var x in parsed) {
arr.push(parsed[x]);
}
return arr[0];
});
}
}
Please try this code (integrated into your original program of course) and let me know if it works or otherwise what is the exact error and what line it occurs on.
I have the big problem. I want to display this json, but returning undefined value.
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
I use this code in service.ts
public getHomeboxPById(id: string): Observable<HomeboxP> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('home_id', id);
urlSearchParams.append('token', this.auth.getCurrentUser().token);
let body = urlSearchParams.toString();
return this.http.post(Api.getUrl(Api.URLS.getHomeboxPById), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return new HomeboxP(res.StatusDescription[0]);
} else if (res.StatusCode === 1) {
this.auth.logout();
} else {
return new HomeboxP(null);
}
});
}
In ts code I call this method getHomeboxPById, like this
editHomeboxPForm: FormGroup;
homeboxp: HomeboxP;
this.editHomeboxPForm = this.fb.group({
'homebox_id': new FormControl('', Validators.required)
});
}
populateFormHomeboxP() {
this.activatedRoute.params.subscribe(
params => {
this.ws.getHomeboxPById(params['id']).subscribe(
homeboxp => {
console.log(homeboxp); // display undefined
this.homeboxp = homeboxp;
this.editHomeboxPForm.controls['homebox_id'].setValue(homeboxp.homebox_id);
}
);
}
);
}
Please, can you help me, why doesn't work?
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
If this is the response of
this.http.post(Api.getUrl(Api.URLS.getHomeboxPById)
Then issue is res.StatusDescription[0] , it should be res.StatusDescription like :
new HomeboxP(res.StatusDescription);
I have a complex object parameter that I need to send as post, as it could be too long for querystring. The post call is asking to have an excel file dynamically generated and then downloaded asynchronously. But all of this is happening inside of a react application. How does one do this using axios.post, react, and webapi? I have confirmed that the file does generate and the download up to the response does come back, but I'm not sure how to actually open the file. I have a hidden iframe that I'm trying to set the path, src, of the file to, but I dont know what response property to use.
// webapi
[HttpPost]
public HttpResponseMessage Post([FromBody]ExcelExportModel pModel)
{
var lFile = ProductDataModel.GetHoldingsExport(pModel);
var lResult = new HttpResponseMessage(HttpStatusCode.OK);
lResult.Content = new ByteArrayContent(lFile);
lResult.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "HoldingsGridExport.xls"
};
lResult.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return lResult;
}
// client side api
static getHoldingsExport({ UserConfigurationID, UserID, Configurations, ViewName, SortModel, FilterModel, UserConfigType, IsDefault, LastPortfolioSearchID = null, ProductId }) {
const filterModel = JSON.stringify(FilterModel); // saving as string as this model is dynamically generated by grid out of my control
const sortModel = JSON.stringify(SortModel);
let params = JSON.stringify({
UserConfigurationID,
UserID,
Configurations,
ViewName,
filterModel,
sortModel,
UserConfigType,
IsDefault,
LastPortfolioSearchID,
ProductId
});
return axiosInstance.post("/api/HoldingsExport", params);
}
// client side app call to get file
HoldingsApi.getHoldingsExport(config)
.then(function(response) {
debugger;
let test = response;
})
.catch(error => {
toastr.success('Failed to get export.');
});
This is how I've achieved file downloads by POSTing via Axios:
Axios.post("YOUR API URI", {
// include your additional POSTed data here
responseType: "blob"
}).then((response) => {
let blob = new Blob([response.data], { type: extractContentType(response) }),
downloadUrl = window.URL.createObjectURL(blob),
filename = "",
disposition = response.headers["content-disposition"];
if (disposition && disposition.indexOf("attachment") !== -1) {
let filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/,
matches = filenameRegex.exec(disposition);
if (matches != null && matches[1]) {
filename = matches[1].replace(/['"]/g, "");
}
}
let a = document.createElement("a");
if (typeof a.download === "undefined") {
window.location.href = downloadUrl;
} else {
a.href = downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
}
}).catch((error) => {
// ...
});
Just in case the above solution does not serve you quite well, here is how I could be able to download videos that are hosted on S3 AWS buckets,
const handleDownload = () => {
const link = document.createElement("a");
link.target = "_blank";
link.download = "YOUR_FILE_NAME"
axios
.get(url, {
responseType: "blob",
})
.then((res) => {
link.href = URL.createObjectURL(
new Blob([res.data], { type: "video/mp4" })
);
link.click();
});
};
And I trigger handleDownload function in a button with onClick.
The url in the function has the video URL from S3 buckets
I am trying to use ng-file-upload to upload files using Angular. I need the byte array to store in our database (I cannot store the uploaded file on the server), but I also need the FormData as well. My problem is that I can only seem to get one or the other (either the byte array or the formdata) but not both.
Here is my Angular code:
$scope.uploadPic = function (file) {
$scope.emrDetailID = 7;
file.upload = Upload.upload({
url: '/SSQV4/SSQV5/api/Document/UploadEMRDocument',
method: 'POST',
data: { file: file, 'emrdetail': $scope.emrDetailID}
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
$scope.imageID = file.result;
});
});
};
Using the code below, I can get the byte array and store it in my database:
public async Task<IHttpActionResult> UploadDocument()
{
var provider = new MultipartMemoryStreamProvider();
await Request.Content.ReadAsMultipartAsync(provider);
var f = provider.Contents.First(); // assumes that the file is the only data
if (f != null)
{
string ClientIP = IPNetworking.GetIP4Address();
var filename = f.Headers.ContentDisposition.FileName.Trim('\"');
filename = Path.GetFileName(filename);
var extension = Path.GetExtension(filename).TrimStart('.');
var buffer = await f.ReadAsByteArrayAsync();
FileImageParameterModel pm = new FileImageParameterModel();
pm.binFileImage = buffer;
//pm.CompanyID = UserInfo.intMajorID;
pm.CompanyID = 10707;
pm.dteDocumentDate = Convert.ToDateTime("4/4/2016");
pm.dteExpiration = Convert.ToDateTime("4/4/2017");
pm.vchUserIP = ClientIP;
pm.vchUploadedbyUserName = UserInfo.Username;
pm.vchFileExtension = extension;
CommonClient = new CommonWebApiClient();
CommonClient.AuthorizationToken = UserInfo.AccessToken;
int imageID = await CommonClient.InsertNewFileImage(pm);
return Json(imageID);
}
else
{
return BadRequest("Attachment failed to upload");
}
}
Using the code below I can get the FormData
var provider = new MultipartFormDataStreamProvider(workingFolder);
await Request.Content.ReadAsMultipartAsync(provider);
var emr = provider.FormData["emrdetail"];
but then I can't get the byte array as using MultipartFormDataStreamProvider wants a folder to store the file.
There's got to be a way to get both. I have been searching the internet for 2 days and all I can find are the two solutions above neither of which solves my issue.
Any assistance is greatly appreciated!
You are thinking way to complicated. Here is some of my code which I used for file upload in AngularJS with .NET
Angular:
function uploadFileToUrl(file) {
var formData = new FormData(); // Notice the FormData!!!
formData.append('uploadedFile', file);
return $http({
url: uploadUrl,
method: 'POST',
data: formData,
headers: {
'Content-Type': undefined
}
}).then(resolve, reject);
function resolve(data) {
$log.debug('data : ', data);
return data;
}
function reject(e) {
$log.warn('error in uploadFileToUrl : ', e);
return $q.reject(e);
}
}
Server:
public Task HandleAsync([NotNull] UploadFilesCommand command)
{
return wrapper.InvokeOnChannel(async client =>
{
// init command
command.Output = new Dictionary<string, int>();
try
{
foreach (var file in command.Files)
{
var request = new UploadFileRequest
{
FileName = file.Name,
FileStream = file.Stream
};
UploadFileResponse response = await client.UploadFileAsync(request);
command.Output.Add(file.Name, response.Id);
}
}
finally
{
// dispose streams
foreach (var file in command.Files)
{
if (file.Stream != null)
{
file.Stream.Dispose();
}
}
}
});
}