I'm trying to upload a file to S3 picked with the filepicker package in flutter web. The backend provides me the link to upload the file, so in theory all I need to do is a PUT request to said link. The problem I'm having is (I think) properly sending the file in the body of the request, because if I upload the file directly to S3 with postman on the provided link, it works.
The code below is what I've been working on, after several iterations. I've tried forming the file with http.MultipartFile.fromBytes but the result is the same. I've also tried to send the request with a normal http.put request, and the error there is when I put a Multipart File in the body, if I try to json.encode, I get an error that it wasn't successful, if I don't encode it, it also gives a type error.
This current code is giving and XMLHttpRequest error, which from what I understand is probably due to a CORS error, the thing is I don't understand how that could be. Any input is appreciated!
Here is the code for uploading the image to the link provided by the backend:
Map<String, String> customHeaders2 = {
"x-amz-server-side-encryption-customer-key":
"",
"x-amz-server-side-encryption-customer-algorithm": "AES256",
"x-amz-server-side-encryption-customer-key-MD5":
"",
"Content-Type": "image/png",
"Accept-Encoding": "gzip, deflate, br",
"Connection": "keep-alive",
"Accept": "*/*",
};
final request = http.MultipartRequest(
'PUT',
//body of the response from request to the backend for the link
Uri.parse(jsonDecode(response.body)["data"]["data"]),
);
request.headers.addAll(customHeaders2);
request.files.add(
http.MultipartFile(
'file',
http.ByteStream.fromBytes(file.bytes!),
file.bytes!.length,
filename: file.name,
//contentType: MediaType('application', 'octet-stream'),
),
);
await request.send().then((value) => print(value.statusCode));
Thanks!
Related
I'm trying to send a request to a server that requires a parameter called 'fid' sent in the header for autherization.
Here's what you can help me with.
Payload to be sent in the header 👇
{ "fid" : "Some alphaNum value", "type": "some type string" }
I would like to know how to use jwt encoding in flutter and how to use that in the header of a request to encode and send this payload across to the server for autherization. I'm planning to use HS256 algo for encoding. Since I'm new to the concept of Jwt, there might be errors in the way I asked this question. Please share your thoughts. I would also like to know how to use the secret key too -- like how to generate the key, and where in the request to send this.
Request 👇
fetchData({required String type, required String fid, String url}) async{
<How to get the json web token>
http.get(url, header : <What do I send here>);
}
you can use http or Dio package for calling API requests in flutter,
you can set headers as follows,
https://pub.dev/packages/dio
https://pub.dev/packages/http
final response = http.get(url,
headers: {HttpHeaders.contentTypeHeader: "application/json", HttpHeaders.authorizationHeader: "Bearer $token"});
I am using http post to send some information and get back the response.
final response = await http.post(
Uri.parse(
"some url"
),
headers: <String, String>{
'email': email,
'callbacktoken': callbacktoken
},
);
When I run this, my execution gets stuck at this codeblock ( I tried putting a print statement in the next line) when the response coming from the backend has header values, however if I send the response with no header from the backend (I am using django at the backend) then the my program runs with no issue.
So my question is how to handle responses with headers and how to extract them?
After a little researching I finally found the issue. My custom header name had space in it "New user" because of which http was not able to parse it. After changing the name to "newuser" everything is working fine.
I'm trying to request a Power BI API using axios.
var configReportInfos = {
method: 'get',
url: `https://api.powerbi.com/v1.0/myorg/groups/${process.env.GROUP_ID}/reports/${process.env.DASHBOARD_ID}`,
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer ' + tokenResponse.accessToken
},
data: {}
};
let reportinfos
try {
reportinfos = await axios(configReportInfos)
tokenResponse['reportInfos'] = reportinfos
}
catch (error) {
console.log(error);
};
Actually I'm getting this error
Request failed with status code 400"
But strangely in Postman I'm getting 200 status.
I'm using same token.
I had the same problem. When l switched content-type in my app to application.json everything worked.
I faced the same issue (not in Axios) and struggled for a few hours.
I was able to make the API call from postman but from my java code I was getting a 400.
Turns out, this was a content issue. My request body had some Cyrillic content and it needed to be encoded before sending.
Postman was doing it by default and hence the requests were going through and responding with 200
I recommend to check your Request Header options in most cases some option is configured wrong.
In your case content-type seems wrong, did you try application/json in both calls.
To configure properly you can check the documentation
Content Type Configuration
I attemp to fetch image from Firebase storage, but have error message:
Alamofire.AFError.responseValidationFailed(reason: Alamofire.AFError.ResponseValidationFailureReason.unacceptableContentType(acceptableContentTypes: ["image/x-xbitmap", "image/jpeg", "application/octet-stream", "image/gif", "image/ico", "image/tiff", "image/x-icon", "image/bmp", "image/x-bmp", "image/x-win-bitmap", "image/png", "image/x-ms-bmp"], responseContentType: "application/json")
My url looks like this: https://firebasestorage.googleapis.com/v0/b/####/o/executors/o4uAQa158nXTvJ5omuxqcRb0e793/products/7DDCEEAC-ED54-4910-B93D-5E40BF411B80
I can download this image via browser.
My image has MIME-type 'image/jpeg':
I found the same situation:
Response Content-Type was missing and acceptable content types
Make sure you set alamofire acceptable content types
Image Response Serializers
These hints didn't help me to fix my bug.
Version of pod:
Alamofire: 5.0.2
AlamofireImage 4.0.2
Initially I used AlamofireImage: productImageView.af.setImage(withURL: url), but it didn't work. Then I began using Alamofire. And into request I pass MIME-type image/jpeg like Content-Type:
And I decided to use this approach to fix bug, but has the same error and I don't understand why(from docs):
If you can see in error-message I have:
responseContentType: "application/json"
So does it have any side effect to fetch image? What I do wrong at all?
Link should be
https://firebasestorage.googleapis.com/v0/b/projectname/o/image.png?alt=media&token=auth_token
replace projectname , image name and token to yours
First, your request headers have nothing do with whether the response is valid, so adding image/jpeg there won't help. Second, your response is return an application/json content type, so adding image/jpeg to the acceptable content types won't help (and image/jpeg is already acceptable). (As an aside, you need to import AlamofireImage to get addAcceptableImageContentTypes to work.)
In the end, you should ensure you're getting the response you expect, as an application/json content type implies you're getting a JSON body, not an image fro your request. When I request the URL you posted, I get this JSON response:
{
"error": {
"code": 400,
"message": "Invalid HTTP method/URL pair."
}
}
So most likely you need to double check how you're supposed to be making the request.
I am currently using Flutter and Dart to try to send an image to a web service, after which I wait for a JSON response. The below links show the Postman request that I am trying to mimic.
An image of Postman with the headers required
An image of Postman with the body
I think the issue I am having is either not setting the headers of my request correctly, or not encoding the image correctly.
Currently I am getting a HTTP 400 error.
I have tried following these suggested solutions on StackOverflow but have been getting the HTTP 400 error.
Any help would be much appreciated!
Try this. I'd suggest creating yourself a plain Dart project, if you haven't already. This way you can test things without the need of the phone emulator, etc.
main() async {
http.MultipartRequest request =
new http.MultipartRequest('POST', Uri.parse(url));
request.headers['Prediction-Key'] = '3f4a......'; // todo - insert real value
request.files.add(
new http.MultipartFile.fromBytes(
'image',
bytes,
filename: 'somefile', // optional
contentType: new MediaType('image', 'jpeg'),
),
);
http.StreamedResponse r = await request.send();
print(r.statusCode);
}
If the file is on disk, not in memory, then use the fromPath named constructor instead. Experiment with different media types. I've used image/jpeg, but you could try application/octet-stream.
As an aside, in your first screenshot you show a content type, but Postman ignores this as the overall content type is overridden by multipart-form. Uncheck that row in Postman to prove this.
There was another question recently on SO, where the server was incorrectly expecting headers to be case sensitive. In postman, try again with lowercase prediction-key to prove that the server doesn't mind lowercase headers (which is what Dart uses).