WebKitFormBoundary uploading a file to S3 using axios FormData - axios

I am trying to upload files to S3, files are successfully uploaded and but when downloaded it contains WebKitFormBoundary
------WebKitFormBoundaryrTBzWaHQntWAtZLX
Content-Disposition: form-data; name="file"
hello world
------WebKitFormBoundaryrTBzWaHQntWAtZLX--
Upload using axios
const formData = new FormData();
formData.append('file', this.file);
this.axios.put(this.formUrl,
formData,
{
headers: {
// 'Content-Type': `multipart/form-data`,
'Content-Type' : 'application/octet-stream',
},
})
.then((res) => {
console.log(res)
}).catch((e) => {
console.error(e)
});
How do I remove boundary

I faced the same issue. But the solution is simple. Here is my code I used to upload the file
axios({
method: "PUT",
url: url,
data: fileToUpload, // NOTE - this is the file not the FormData Object
headers: {
"Content-Type": "multipart/form-data" }
})
.then(res => {
this.setState({
uploadSuccess: "File upload successfull",
error: undefined
});
})
.catch(err => {
console.log(err)
});
What really happens is when you attach the file to FormData the FormData get serialized and that serialized data is stored in S3. That's why the file become corrupted.
In the solution we don't wrap the file inside a FormData object. What we do is we directly add the file to data attribute. So nothing other than the file itself get serialized and stored in S3.
Hope this answer would help

Related

Axios request with Contact forms 7

I'm using contact forms 7, and in my form submission I use this function:
const formData = {
'your-name':'John Doe',
'your-email': 'johndoe#mail.com',
}
axios({
method: 'POST',
url: 'https://0xsociety.com/wp-json/contact-form-7/v1/contact-forms/258/feedback',
headers: {
"content-type": "multipart/form-data",
},
data: formData,
})
But it doesnt work, i get errors saying fields are empty.
But I tried with postman and it works perfectly when i do it manually
How would I get my axios post request to mimic this:
https://gyazo.com/e1ffe5bcc3f943a074d9b9e2c32b162d
I figured this out by using postman in my app:
import request from 'postman-request'
const formData = {
'your-name': name,
'your-email': email,
'your-subject': inquiries.find(x=> x.value === inquiry).text,
'file-871': file
}
request.post('https://your-domain/wp-json/contact-form-7/v1/contact-forms/your-form-id/feedback',{ form: formData}, function(err,httpResponse,body){
if(err) {
console.log(err)
}
else {
console.log(body)
}
})

How to store downloaded file local url in mongodb

i want to store the url path of downloaded file in mongodb so i can later use the path to open the file in my app.
i tried to store but the problem is whenever i download new file it upadate with the previous one .
this is the backend code
router.post('/download',function (req, res) {
console.log(req.body)
User.updateOne({_id:req.body.userid},{$set:{downloadurl:req.body.downloadurl
}}).then((user)=>{
console.log(user);
res.status(200).send({
data:user,
message:'success'
})
}).catch((err)=>{
console.log(err)
res.status(500).send({
data:err,
message:'not success'
})
})
});
this is the backend of ui
export async function DownloadUrl(data) {
let result = await fetch(url + 'user/download', {
method: 'POST',
body: JSON.stringify(data),
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
}
}).then(response => response.json());
console.log(result);
return result;
}
The problem here is that your urls are being stored in a plain text field. You need to store them in an array and, instead of using $set, that will overwrite the previous data, start using $push, that will append data to your url array:
router.post('/download',function (req, res) {
console.log(req.body)
User.updateOne(
{_id:req.body.userid},
{$push:{download_urls:req.body.downloadurl}}
).then((user)=>{
console.log(user);
res.status(200).send({
data:user,
message:'success'
})
}).catch((err)=>{
console.log(err)
res.status(500).send({
data:err,
message:'not success'
})
})
});
This way, you will end up with a User document like the one below:
{
"_id": "some_id_value",
// [...]
"dowload_urls": [
"someurl1",
"someurl2",
"someurl3"
]
}

Post to given endpoint as multipart file

I've got working backend in Spring Boot with JWT-secured endpoint for modifying avatar of current user. The following request from Insomnia with correct Bearer works fine:
But this code
updateAvatar(context, avatar) {
const fd = new FormData();
fd.append('file', avatar.data);
return new Promise((resolve, reject) => {
axios.post('/saveavatar',
{file: fd},
{headers: {'Authorization': 'Bearer ' + localStorage.getItem('access_token')}})
.then(response => {
resolve(response)
})
.catch(error => {
reject(error)
})
})
},
fails with error
the request was rejected because no multipart boundary was found
What am I doing wrong?
The second argument to post should be the actual FormData, fd in your case.
axios.post('/saveavatar',
fd,
{headers: {'Authorization': 'Bearer ' + localStorage.getItem('access_token')}})
The reason it works in Insomia is that it takes care of your request and figures out that it needs to ads a boundary, axios will do the same, but needs a valid FormData.

File not uploading in server ionic3

I have a scenario where I am uploading a image file from my local drive (type jpeg or png) to an API endpoint using ionic. Here is my code below :
fileupload.html -->
//---------------------------------------------------
<ion-item>
<ion-input type="file" accept="image/*" (change)="changeListener($event)"> </ion-input>
</ion-item>
fileupload.ts -->
changeListener($event):void{
this.file=$event.target.files[0];
console.log(this.file);
console.log("upload...");
let regData={"file":this.file};
console.log("REGDATAA"+JSON.stringify(regData));
this.jira.postAttachment("PM-3",regData).subscribe(dataa=>{
console.log(dataa);
});
}
provider.ts -->
public postAttachment(key,data):Observable<any>{
console.log(JSON.stringify(data))
return this.http.post(this.api+'/issue/'+key+'/attachments',JSON.stringify(data),{
headers: new HttpHeaders()
.append('Authorization', `Basic ${this.auth.getAuthString()}`)
.append('Content-Type','multipart/form-data';boundary="-------xe3rtyhrfds")
.append("X-Atlassian-Token", "no-check")
.append("User-Agent", "xx")
});
}
every time I send the file it doesn't take the path and sends an empty response, here is the error below.
//----------------------------------------------------
[object File]: {lastModifiedDate: [date] Fri Sep 21 2018 17:42:46 GMT+0530 (India Standard Time), name: "download.jpg", size: 5056, type: "image/jpeg", webkitRelativePath: ""}
upload...
ion-dev.js (157,11)
REGDATAA{"file":{}}
ion-dev.js (157,11)
{"file":{}}
ion-dev.js (157,11)
ERROR [object Object]
I have resolved CORS issue and there is no problem with the same.
When I send the same response using postman it succeeds here is what I send in Postman.
Form-data
key - "file" (type file) value - "/path/to/my/file"
Headers
Content-type - application/json
x-attlassian token - no-check
Can somebody advice what is going wrong here.
Use FormData to upload file.
fileupload.ts
changeListener(event) {
const fd = new FormData();
this.file = event.target.files[0];
fd.append('file', this.file, this.file.name);
this.jira.postAttachment("PM-3",fd)
.subscribe(data => {
console.log(data);
});
}
provider.ts
postAttachment(key, fd): Observable<any> {
const httpOptions = {
headers: new HttpHeaders(
{ 'Content-Type': 'multipart/form-data' },
{ 'Authorization': `Basic ${this.auth.getAuthString()}` })
};
return this.http.post(this.api+'/issue/'+key+'/attachments', fd, httpOptions);
}
Your have to change the content type from application/json to multipart/form-data. You are sending an image, not a json-file.
Best way is to encode your image to base64 and send it. Everything depends about what your server needs.
or you can try this.
const body = file;
const headers = new Headers({'Content-Type': 'image/jpg'});
return this.http.post(this.api+'/issue/'+key+'/attachments, body, {headers: headers}). ...
For an issue on AngularJS what ended up working is (might a similar aproach help you too) :
make a hidden input de type file
set it's value in the changeListener function
make the file send from there afterwards
The reason being some built in propertie of the file input let's its value be recognised as File/Blob instead of the path many "complex" components use.
Also send it as multipart file as mentioned before.

Upload image from data url to Axios?

Ive been uploading image files to an API (Graphcool) with this, and everything was working fine:
fileUpload(file) {
let data = new FormData();
data.append('data', file);
axios
.post(`https://api.graph.cool/file/v1/MY-PROJECTID`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
console.log(res)
});
}
In the code above the file was passed from a <input type="file" />
However now I'm using React Avatar Editor to allow users to crop images and ensure they are a square:
https://github.com/mosch/react-avatar-editor
When you access the image from React Avatar Editor it comes in the form of a data url (via Canvas.toDataURL()).
How can I upload a data url with Axios? Do I need to first convert the image to an actual 'file' in the browsers memory?
This is a duplicate of below thread just in a different language
Sending canvas.toDataURL() as FormData
You need to change your code like below
function fileUpload(canvas) {
let data = new FormData();
canvas.toBlob(function (blob) {
data.append('data', blob);
axios
.post(`https://api.graph.cool/file/v1/MY-PROJECTID`, data, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.then(res => {
console.log(res)
});
});
}