Hello to everyone i hope you all good.
Im trying to upload a image to a server im using this:
But it dosent work. So please help me, i would really appreciate it.
Future<int> uploadFile(imageFile) async {
try {
var request = http.MultipartRequest(
'POST',
Uri.parse('http://10.0.2.2:8000/objects/'),
);
Map<String, String> headers = {"Content-type": "multipart/form-data"};
request.files.add(
http.MultipartFile(
'file',
imageFile.readAsBytes().asStream(),
imageFile.lengthSync(),
contentType: MediaType(
'image',
'jpeg',
),
),
);
request.headers.addAll(headers);
request.fields.addAll({
"app_label": "files",
"app_model": "file",
});
print("request: " + request.toString());
var res = await request.send();
print("This is response:" + res.toString());
return res.statusCode;
} catch (err) {
print(err);
return 502;
}
}
Response from the server and vscode:
https://ibb.co/2SMTBxJ
You can check the project here:
https://github.com/bRUNS123/hydra
Also if someone know how to put the image without crop like the "finished" file.
I the app you can take an image from the gallery or camera, then you have a preview and you can send or save to the gallery. But i created an option to avoid the crop image, but when i try to pass the information to not crop, nothing happen.
Also i wanna know if i can put all my void functions in a separated file.
Hope you have a great day!!
Related
I'm trying to create a flutter app that will allow a user to upload an image and a brief description of said image, and if I test my server code with either Thunder Client or Chrome, it works great, but if I try either the MultipartRequest or Dio from a Flutter app, the image seems to be included in the list of text fields, and the "files" part of the form object is empty. This happens no matter whether I try to upload an image or a small text document. Here is my Flutter code:
ElevatedButton(
child: const Text("Submit Report"),
onPressed: () async {
var dio = Dio();
var formData = FormData.fromMap({
"description": "This is a description",
"location": "This is a location",
"image": MultipartFile.fromBytes(
utf8.encode("hello, world"),
filename: "hello.txt",
contentType: MediaType("text", "plain")),
});
var response = await dio.post(
"${dotenv.env['SUPABASE_FUNCTIONS_URL']!}/hello-world",
data: formData,
);
debugPrint("***${response.statusCode}***");
},
)
If I debug and look at the Network tab in Dart's DevTools, I can see the request headers are set like they should be (Content-Type is multipart/form-data and a boundary is set). My server is just a small Deno function using the multiParser library running on Supabase:
serve(async (req) => {
const form = await multiParser(req);
console.log(form);
return new Response(
JSON.stringify(form),
{ headers: { "Content-Type": "application/json" } },
);
})
If I look at the invocation logs on Supabase, the requests coming from Thunder Client and Chrome look fine; the fields and files are populated the way they should be. Meanwhile, coming from Flutter (Dio and MultipartRequest yield the same result), the console.log(form) from above looks like this:
{
fields: {
description: "This is a description",
location: "This is a location",
'image"; filename="hello.txt"\r\ncontent-type: text/plai': "hello, world"
},
files: {}
}
I have tried manually setting various headers (like Content-Type), tried both the MultipartRequest and Dio approaches, and tried manually tweaking the file being uploaded (content type as well as file body). Also tried both running in an emulator as well as on a real Android phone. The result is always the same.
Used Oak's multipart/form-data parser instead, and it works with everything. Seems to be some sort of incompatibility between MultipartRequest/Dio and multiParser. Thanks to #pskink for troubleshooting with me.
I am a newbie and am attempting to display an image that is from my Github profile vs hardcoding it into the HTML. Currently, I have coded the following and the object is being displayed in my Javascript console.
const APIURL = 'https://api.github.com/users/'
getUser('JetimLee')
async function getUser(username) {
try {
const {
data
} = await axios(APIURL + username)
console.log(data)
} catch (err) {
console.log(err)
}
}
My question is - how do I get the image from the profile to be displayed? Thank you so much in advance!
You have an avatar_url field, set it's value as source of an image tag in your html.
Example:
const data = await axios('link');
const imgTag = document.getElementById('git-user-id');
imgTag.setAttribute('src', data.avatar_url);
Is there any way to get files like .pdf downloaded directly on user's device instead of opening this pdf in the browser?
This code works for downloading non browser supported files but it opens pdf, mp3, etc. in the browser.
final anchor = AnchorElement(
href: pickedFile)
..setAttribute("download", fileName)
..click();
If someone is still searching for solution.Here is what I have done.
Anchor tag will directly download file if it has download attribute.
Note: Download attribute is only supported for same-origin request
So instead of assigning external URL link to anchor element. Create Blob object from PDF data and create Object URL from that.
var url = Url.createObjectUrlFromBlob(Blob([data]));
AnchorElement(href: url)
..setAttribute('download', '<downloaded_file_name.pdf>')
..click();
I am using Firebase to store file so here is the complete code.
FirebaseStorage.instance.ref(resumeFileName).getData().then(
(data) {
var url = Url.createObjectUrlFromBlob(Blob([data]));
AnchorElement(href: url)
..setAttribute('download', '<downloaded_file_name.pdf>')
..click();
}
);
by following the steps below, you can download the file automatically by the browser and save it in the download directory.
In this method, http and universal_html packages are used.
The important thing is to manage Multiplatform-Mode and using this code, is better you create 3 separate dart files.
switch_native_web.dart
web.dart
native.dart
/// switch_native_web.dart
import 'native.dart' if (dart.library.html) 'web.dart' as switch_value;
class SwitchNativeWeb {
static void downloadFile({required String url,
required String fileName ,required String dataType}){
switch_value.downloadFile(dataType: dataType,fileName: fileName,url: url);}
}
...
/// web.dart
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:universal_html/html.dart' as universal_html;
Future<void> downloadFile(
{required String url,
required String fileName,
required String dataType}) async {
try {
// first we make a request to the url like you did
// in the android and ios version
final http.Response r = await http.get(
Uri.parse(url),
);
// we get the bytes from the body
final data = r.bodyBytes;
// and encode them to base64
final base64data = base64Encode(data);
// then we create and AnchorElement with the html package
final a =
universal_html.AnchorElement(href: '$dataType;base64,$base64data');
// set the name of the file we want the image to get
// downloaded to
a.download = fileName;
// and we click the AnchorElement which downloads the image
a.click();
// finally we remove the AnchorElement
a.remove();
} catch (e) {
print(e);
}
}
...
/// native.dart
Future<void> downloadFile({required String url, required String fileName,
required String dataType}) async {}
And using the following sample code for calling the downloadFile method wherever you need:
...
GestureDetector(
onTap: () => SwitchNativeWeb.downloadFile(
url: "https://... your url ..../download.jpg",
fileName: "download.jpg",
dataType: "data:image/jpeg"),
child: Text('download')
)
...
I only wrote the code related to web download (according to the question), you can write the code related to ios and android download in the native .dart file.
Use Dio Library.
dependencies:
dio: ^3.0.10
to download file
response = await dio.download("https://www.google.com/", "./xx.html");
this video will help you.
I need to pass an image file that I have taken from the camera, directly as param with a POST method in Flutter.
You can use MultipartFile from the http library
var request = http.MultipartRequest('POST', Uri.parse('YourUrl'));
request.files.add(
http.MultipartFile.fromBytes(
'YourField',
File('YourFilename').readAsBytesSync(),
filename: 'YourFilename'
)
);
var res = await request.send();
In my case I want to send video to my host through post request.
I finish of many steps:
1- I can get a video file from the gallery with File Data Type. (Using image_picker).
videoSelectorGallery() async {
VideoFile = await ImagePicker.pickVideo(
source: ImageSource.gallery,
);
_videoPlayerController = VideoPlayerController.file(VideoFile)..initialize().then((_) {
setState(() { });
});
print("You selected gallery video : " + VideoFile.path);
.
.
.
}
2- I change it to String64bytes.
.
.
.
// Convert from file to String64byte
videoBytes = await VideoFile.readAsBytesSync();
base64Video = base64Encode(videoBytes);
print(base64Video);
}
3- I send String64bytes with post request.
.
.
.
var body = json.encode(
{
"shopName":...,
"description":...,
"typeID":...,
"video": base64Video // <---- String64bytes
}
);
.
.
.
The problem : When I send this request, it gets very long time to finish and the reason because the video has large size.
I think the best way to send faster is to compress the video but I don't know how and I search before about compressing videos useing flutter, I found some ways but still not work for me.
Any one know beeter idea how to send faster or good way to compress ?