Aurelia js fie upload to server - aurelia

Hi am new to aurelia js , i need to upload file to server,am using autrelia js, materializecss and httpClient.fetch for api call. I dont'know how to send file to server.
view :
<input type="file" files.bind="selectedFiles" change.delegate="onSelectFile($event)">
Model :
onSelectFile(e)
{
var myurl = 'http://cdn.dmsapp.tk/file?authToken=bLNYMtfbHntfloXBuGlSPueilaHtZx&type=jpg&name=sibi.jpg&userId=7&organizationId=1&sourceType=USER_UPLOADS';
this.httpValueConverter.call_http(myurl,'POST',this.selectedFiles[],'fileupload',file_upload)
.then(data => {
console.log(data);
if(data.meta && data.meta.statusCode == 200) {
// this.index_lists = data.index.list;
}
}); }
httpservice :
return this.httpClient.fetch('http://api.dmsapp.tk/'+url,
{
method: method,
body : json(myPostData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'authorization': this.authorization}})
.then(response => response.json());
looking for a solution.

If it's a file and you are trying to upload a particular media type,
the header 'Content-Type': 'application/x-www-form-urlencoded' does not seem right to me. Have a look at the appropriate media type here:
http://www.iana.org/assignments/media-types/media-types.xhtml
Also, you serialize data to JSON, if your data is binary you will need to change that to a byte array.
You might find some useful info here:
http://www.petermorlion.com/file-upload-with-aurelia/
Also you set a token both in your URL and your header, I'd recommend to set it in the header only.

Related

Upload to S3 - The body of your POST request is not well-formed multipart/form-data

I am trying to upload a file to s3 using this guide: https://www.dtreelabs.com/blog/s3-direct-file-upload-using-presigned-url-from-react-and-rails which long story short describes how to use a presigned url to upload files to S3.
Whenever I send the request to my s3 bucket to upload a given file, I am getting an error The body of your POST request is not well-formed multipart/form-data.
My front end code is:
const handleImageUpload = (file) => {
ApiUtils.getPresignedS3Url({ fileName: file.name }).then((uploadParams) => {
if (uploadParams) {
uploadToS3(uploadParams, file)
}
})
const uploadToS3 = (uploadParams, file) => {
const { url, s3_upload_params: fields } = uploadParams
const formData = new FormData()
formData.append("Content-Type", file.type)
Object.entries(fields).forEach(([k, v]) => {
formData.append(k, v)
})
formData.append("file", file)
fetch(url, {
method: "POST",
headers: {
"Content-Type": "multipart/form-data",
},
undefined,
body: formData,
})
.then((awsResponse) => {
if (awsResponse.ok) {
console.log("success")
} else {
console.log(awsResponse)
}
})
.catch((error) => {
console.log("blew up")
console.log(error)
})
}
Several other stack overflow answers involve using Axios or new XMLHttpRequest. These have resulted in the same error for me.
the end of the payload I am sending to amazon is:
------WebKitFormBoundary7cFRTGgKGqbDhagf
Content-Disposition: form-data; name="file"; filename="uploadMe.html"
Content-Type: text/html
------WebKitFormBoundary7cFRTGgKGqbDhagf--
I believe the issue may be something along the lines of the body of my file isn't being included in the request. I'm investigating this now.
Any help would be appreciated, thank you <3
https://github.com/github/fetch/issues/505#issuecomment-293064470 describes why this is an issue. Posting the text incase the comment ever gets removed:
Setting the Content-Type header manually means it's missing the boundary parameter. Remove that header and allow fetch to generate the full content type. It will look something like this:
Content-Type: multipart/form-data;boundary=----WebKitFormBoundaryyrV7KO0BoCBuDbTL
Fetch knows which content type header to create based on the FormData object passed in as the request body content.
removing "Content-Type": "multipart/form-data" above indeed seems to result in the mujltipart form data being formatted correctly.

Image upload in React Native (Expo), using fetch results in 400 error

I have been struggling with image upload for days.
I’m using formdata like this:
let formData = new FormData();
formData.append('file', {
uri: uri,
name: `name`,
type: `image/jpeg`,
});
uri on iOS is something like asset-library://asset/path on Android it is like content://media/external/images/media/25377.
let options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Authorization': 'Bearer ' + token,
},
};
let response = await fetch("https://myserverurl", options)
I tried every trick reading the image as blob, removing content-type, other libraries like axios, etc…
No matter what I always get back a 400 bad file format error.
Is there something I’m missing with formdata?
(On the backend we use ASP.NET)
We have had a similar issue and were able to solve the issue the following way.
We are using a NodeJS backend (with multer) to handle the file uploads.
Expo - Mobile App Code
// extract the filetype
let fileType = uri.substring(uri.lastIndexOf(".") + 1);
let formData = new FormData();
formData.append("photo", {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`
});
let options = {
method: "POST",
body: formData,
headers: {
Accept: "application/json",
"Content-Type": "multipart/form-data"
}
};
We are executing the request with fetch(apiUrl, options).
The uri is the local file path (full URI e.g., file:///...) of the photo in our case and apiUrl is the endpoint of the server-side.
I think the issue might be with the type and format of uri in formdata. Have you tried to use the uri returned by the image picker?

Post to /upload from react native

I'm trying to upload a picture to strapi from react native.
async function uploadPicture(uri) {
var data = new FormData();
data.append('files', {
uri: uri.replace('file://', ''),
name: uri,
type: 'image/jpg'
});
// Create the config object for the POST
// You typically have an OAuth2 token that you use for authentication
const config = {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data;'
},
body: data
};
const fetchPromise = fetch('http://<host>:1337/upload', config)
console.log(fetchPromise)
return await fetchPromise
}
I get a 200 status code but no new picture is listed on the uploads page.
Oh! I figured it out using simple-http-upload-server to test the uploads. The problem was that I was setting the name of the file to be the uri. This would probably cause an error on strapi when creating the file on the server folder. It should return an error code nonetheless.

Upload Images With Aurelia to Express/Multer Api

Implementing an Image/File-Upload into my aurelia App. The Express Api works and successfully receives Files and Images using Multer Plugin, tested with Postman.
Now I'm trying to figure out, how to attach the files ot the Aurelia Http/Fetch-Call. Somehow the request is made to the Api, but the images seem not attached. Any Ideas?
Some questions:
Is it correct to attach - in whatever way - the files to the body-key of the request, or do the files need to go seperately?
Is it correct/neccessary to create FormData and to attach the files - in whatever way - to that Obejct?
In what part of the HTTP-Request are the files/images stored, how to identify them serverside (in case my middleware is not working correctly)?
This is my approach so far:
Aurelia-Service:
uploadImagesApi(images) {
let formData = new FormData()
formData.images = images;
return http.fetch(url+"/", {
method: 'put',
body: formData, // <-- Is this correct?
}).then(response => {
return response
}).catch(error => {
console.log("Some Failure...");
throw error.content;
})
}
Input-Element
<input class="input" type="file" files.bind="images" multiple>
<a click.delegate="uploadImagesApi(images)">Upload</a>
uploadImagesApi(images) {
let formData = new FormData()
for (let i = 0; i < images.length; i++) {
formData.append('images', images[i]);
}
return http.fetch(url + "/", {
method: 'put',
body: formData,
})
.then(response => {
return response
})
.catch(error => {
console.log("Some Failure...");
throw error.content;
})
}
make sure your url variable is defined looks like a global
Change formData.images = images; to formData.images = images.item(0);
It might also be required to use 'file' key in formData instead of 'images': formData.file = images.item(o)

Post 'x-www-form-urlencoded' content with aurelia-fetch-client

The question is simple: how do I post x-www-form-urlencoded content with Aurelia Fetch client?
I need to make the post to a simple ASP.NET Web API server that is using OWIN and Katana for authentication.
An example of what I have already tried:
var loginDTO = new FormData();
loginDTO.append('grant_type', 'password');
loginDTO.append('email', 'test');
loginDTO.append('password', 'test');
return this.http
.fetch(config.router.token, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: loginDTO
});
Obviously, that didn't work as intended. How is the correct way to go about posting the data presented in the example?
The aurelia-fetch-client is built on Fetch specification, and it seems that Fetch always sends FormData as Content-Type: multipart/form-data.
To get around this, you have to convert the parameters to a query string and then set the content-type to x-www-form-urlenconed. You can use jQuery or a custom function to convert the object to a query string. Like this:
//jQuery.param returns something like ?param=1&param2=2 and so on
//params = a plain javascript object that contains the parameters to be sent
this.http.fetch(url, {
body: $.param(params),
method: 'post',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(response => response.json())
.then(response => {
//your magic here
});
Not a good solution, I know, but that's the easiest way I found so far.
You would use FormData like this:
function sendForm() {
var formData = new FormData();
formData.append('email', 'test#test.com');
formData.append('password', '123456');
http.post(url, formData);
}