Angular 8 can't upload formdata/multi-part to server - http-post

I'm trying to upload a xlsx file to server, but I receive two different errors, whether I specify the contentType in the http request header or not. If I specify "Content-type: multipart/form-data" I get the following error:
FileUploadException: the request was rejected because no multipart
boundary was found
Then, if I do not specify the content type (as proposed in different answers), I get this error:
current request is not a multipart request
This is what I do to upload the file. HTML (input fired by a button that calls an uploadFile() method):
<input type="file" #fileUpload id="fileUpload" name="fileUpload" accept=".xlsx" style="display:none;" />
.ts:
uploadFile() {
const fileUpload = this.fileUpload.nativeElement;
fileUpload.onchange = () => {
this.file = fileUpload.files[0];
this.uploadFileToServer();
};
fileUpload.click();
}
uploadFileToServer() {
const formData = new FormData();
formData.append('file', this.file);
this.importService.uploadFile(formData).subscribe(d => {
});
}
In the service the method does this:
this.http.post(
apiUrl,
formData,
options
);
where in options there are the specified headers:
let applicationHeaders = new HttpHeaders();
applicationHeaders = applicationHeaders.append('Content-type', 'multipart/form-data');
multipart or blank.
In the POST request in the request payload I have:
------WebKitFormBoundarytNckytdr7I8wQcuc
Content-Disposition: form-data; name="file"; filename="Template (2).xlsx"
Content-Type: application/octet-stream
------WebKitFormBoundarytNckytdr7I8wQcuc--

Related

Handling base64 string as application/pdf for a single endpoint on API Gateway

We have an API that has multiple different endpoints, as you'd expect. We have the requirement to add a new endpoint which will return an application/pdf along with the file data.
To do this, we return the following:
return {
statusCode: 200,
headers: {
'Content-Type': 'application/pdf',
'Content-disposition': `attachment; filename=${filename}.pdf`,
'Accept': 'application/pdf',
},
body: fileData,
isBase64Encoded: true,
};
The isBase64Encoded only works when a binary media type is set in the API Gateway. As detailed here:
https://medium.com/#ngchiwang/aws-api-gateway-lambda-return-binary-image-ba8faa660839
The issue we have is that by setting the binary media type to * / * (no spaces) on the API Gateway, this, in turn, affects all other endpoints on the API.
Example This breaks one endpoint on the OPTIONS cors check, returning an InternalServerErrorException without reason. This endpoint is just a GET with no data in the request.
Does this mean we need a separate API just for this one endpoint, or is there a way we can include this in the same APIG?
For further clarification, this is a POST that includes a small amount of JSON in the request: {"someValue":1234} and returns the above application/pdf content type.
I'm just tackling this issue and resolved it like this:
Send base 64 string just as normal json response and handle the pdf part on the client
const sendRes = (status:number, body:any) => {
var response = { statusCode: status, headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
return response;
};
return sendRes(201, {pdf:your-base64-string} );
Then on the client (Nuxt in my case):
let res = await this.$store.dispatch('pdf/makePdf')
const linkSource = `data:application/pdf;base64,${res.data.pdf}`;
const downloadLink = document.createElement("a");
const fileName = "your-pdf-filename.pdf";
downloadLink.href = linkSource;
downloadLink.download = fileName;
downloadLink.click();
This open a download window and lets you save the file locally

Laravel can not understand formData parameters

According to this question:
Angular5 HttpClient send data but server can not understand its params
I send username, password and _token parameters to server through FormData in angular5. I set header to
'Content-Type': 'application/x-www-form-urlencoded'
now, I faced another problem in server.
Request header changed to
------WebKitFormBoundaryGOu5izF9uMKIXDW1
Content-Disposition: form-data; name:"username"
a#a.com
------WebKitFormBoundaryGOu5izF9uMKIXDW1
Content-Disposition: form-data; name="password"
123456
------WebKitFormBoundaryGOu5izF9uMKIXDW1
Content-Disposition: form-data; name="_token"
[object Object]
------WebKitFormBoundaryGOu5izF9uMKIXDW1--
Now, Laravel could not read request parameters in this way:
$request->input('username') // returns null
$request->input() // returns whole request content, not an object or array
How could I read request parameters ?
e.g. Is there any regular expression that can help me? or any patches in higher Laravel versions that I can use?
Laravel version: 5.2
Does your controller in Laravel have these included?
use Illuminate\Http\Request;
use Illuminate\Http\Response;
and does your function look like this?
public function signIn(Request $request, Response $response){
$output = $request->input('username');
return $output;
}
What we are doing above is getting the output of the response which we are wanting username and return that so you should get the username back
EDIT
Does your Angular service look like this
login(username:string, password:string) {
let formData = new FormData();
formData.append('username', username);
formData.append('password', password);
return this._http.post(
'http://oauth-api/api/me/signin',
formData
);
}

Http multipart request using Google Drive API

I am trying to send HTTP multipart request using Google Drive API to insert file in Google Drive.
I am following the link below : Multipart upload
However, I am getting a Bad request error.
Below is the request string which I have created using the documentation link above:
String content = '\r\n--' + boundary + '\r\n';
content +='Content-Type: '+'application/json; charset=UTF-8'+'\r\n\r\n';
content +='{' + '\r\n';
content +='"title": "My File"'+'\r\n';
content +='}'+'\r\n\r\n';
content += '--'+boundary + '\r\n';
content +='Content-Type: '+'text/plain'+'\r\n';
content += EncodingUtil.base64Encode(b)+'\r\n';
content += '-'+boundary+'-\r\n';
Please can someone tell me what I am missing here ??
I was having trouble with this as well,
but if you look at the code for the google drive API on github:
Github Drive API
The request parameters accept a media object, which can have a body and mimeType.
I was working with a service account, and this lets you upload files directly to drive.
auth.getApplicationDefault(function(err, authClient) {
if (err) {
console.log('Authentication failed because of ', err);
return;
}
if (authClient.createScopedRequired && authClient.createScopedRequired()) {
var scopes = ['https://www.googleapis.com/auth/drive'];
authClient = authClient.createScoped(scopes);
}
var request = {
project: "YOUR_PROJECT",
auth: authClient,
resource: {
parents: ['blah']
},
media: {
body: 'hi',
mimeType: 'text/plain'
}
};
drive.files.create(request, function(err, result) {
if (err) {
console.log(err);
} else {
console.log(result);
}
});
});
I had this problem too and after trying some changes I finally reached a working example:
Header :
POST /upload/drive/v2/files?uploadType=multipart&access_token=ya29.CjAmA2j6eonCiROaNum-V1cWdFVH2vXpNiXAsXK6iLPu7K54tD4uNsmH-eEycMcnaBE HTTP/1.1
Host: www.googleapis.com
Accept: */*
Content-Type: multipart/related; boundary="foo_bar_baz"
Content-Length: 150
remember to add boundary="foo_bar_baz" in Content-Type field
Body :
--foo_bar_baz
Content-Type: application/json; charset=UTF-8
{
"title": "My File"
}
--foo_bar_baz
Content-Type: text/txt
JPEG data
--foo_bar_baz--

Facebook graph api: upload multipart/form-data encoded image

I am trying to post an image using the source parameter (Multipart/form-data) in the Graph API explorer. My source parameter looks like this:
{Content-Type: multipart/form-data; boundary=xxxsrixxx
--xxxsrixxx
Content-Disposition: attachment; filename=try2.gif
Content-Type: image/gif
Content-Transfer-Encoding: binary,base64
R0lGODlhXgExAYeAAQAAAAEBAQICAgMDAwQ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B48OSn4ZeHgSVLku06OwhLyMH6eZR6JQOHdd06evh55oeHJze6bpRLlYhqqD+Heq8I3ta6uUhDC1wA6H5kKq+HoLAARKACLaQDDDwMLG+67ze677+68Ae7MI+7MRe7MZ+7Mie7Mq+7Mze7M7+7NAe7dKOKAAAIf8LUElBTllHSUYxLjAWSW1hZ2UgZnJvbSBjbGlwYm9hcmQBIAA7
--xxxsrixxx--}
This always seems to return
{
"error": {
"message": "(#324) Requires upload file",
"type": "OAuthException",
"code": 324
}
}
Few questions:
Does facebook source parameter accept base64 encoded image data?
Has anyone tried using the source parameter in the graph api explorer and have a working sample?
should the source param value should be url-encoded?
Note: My access token has all the required permissions and if i am not wrong, my encoding seems to be wrong. The base64 encoded text above is a complete image and i could decode it and get the image.
Ok. This is going to sound crazy. After a week of trying I was able to post an image successfully to the facebook wall. The fix was to send the raw binary data as it is (no base64 encoding - fb does not like it) and make sure your multipart/form-data is correct. For instance, if you boundary is defined as "boundary=--xxxsrixxx" your actual request should look like this "----xxxsrixxx\r\nContent-Disposition......\r\n----xxxsrixxx"
This works fine for me, it only uses native JavaScript features and a file input:
const fileReader = new FileReader();
const file = document.getElementById('imageInput').files[0];
fileReader.onloadend = async () => {
const photoData = new Blob([fileReader.result], {type: 'image/jpg'});
const formData = new FormData();
formData.append('access_token', pageAccessToken);
formData.append('source', photoData);
formData.append('message', 'some status message');
let response = await fetch(`https://graph.facebook.com/${pageId}/photos`, {
body: formData,
method: 'post'
});
response = await response.json();
console.log(response);
};
fileReader.readAsArrayBuffer(file);
More information: http://www.devils-heaven.com/facebook-javascript-sdk-photo-upload-with-formdata/

IE striping headers from HTTP POST request to S3

I'm doing straight-to-S3 multipart file upload via AJAX. Everything works fine under all browsers but IE.
S3 requires an Authorization HTTP header in each POST request which contains the signature of the file slice being uploaded.
It appears IE strips out this header from the request, yielding a 403 response.
What's more funny is that IE does not strip another custom S3 header: x-amz-date.
Any idea how I can force the 'Authorization' header in?
As requested, here is my code :
initiateUpload: function() {
var response = this.sign({method:'POST', path: this.key + '?uploads'});
this.request({
method: 'POST',
url: response.url,
headers: {
'x-amz-date': response.date,
'Authorization': response.signature
},
onLoad: this.uploadParts.bind(this)
});
},
request: function(params){
var xhr = new XMLHttpRequest();
if (params.onLoad) xhr.addEventListener("load", params.onLoad, false);
if (params.onUploadStart) xhr.upload.onloadstart = params.onUploadStart;
if (params.onUploadProgress) xhr.upload.onprogress = params.onUploadProgress;
xhr.open(params.method, params.url, true);
for (h in params.headers)
xhr.setRequestHeader(h, params.headers[h]);
xhr.send(params.body);
},

Resources