Can we use dart to download a file?
For example in python
I'm using the HTTP package a lot. If you want to download a file that is not huge, you could use the HTTP package for a cleaner approach:
import 'package:http/http.dart' as http;
main() {
http.get(url).then((response) {
new File(path).writeAsBytes(response.bodyBytes);
});
}
What Alexandre wrote will perform better for larger files. Consider writing a helper function for that if you find the need for downloading files often.
Shailen's response is correct and can even be a little shorter with Stream.pipe.
import 'dart:io';
main() async {
final request = await HttpClient().getUrl(Uri.parse('http://example.com'));
final response = await request.close();
response.pipe(File('foo.txt').openWrite());
}
The python example linked to in the question involves requesting the contents of example.com and writing the response to a file.
Here is how you can do something similar in Dart:
import 'dart:io';
main() {
var url = Uri.parse('http://example.com');
var httpClient = new HttpClient();
httpClient.getUrl(url)
.then((HttpClientRequest request) {
return request.close();
})
.then((HttpClientResponse response) {
response.transform(new StringDecoder()).toList().then((data) {
var body = data.join('');
print(body);
var file = new File('foo.txt');
file.writeAsString(body).then((_) {
httpClient.close();
});
});
});
}
We can use http.readBytes(url).
await File(path).writeAsBytes(await http.readBytes('https://picsum.photos/200/300/?random'));
Yes, first of all you have to request to file url using http dart library like:
Response response = await get(Uri.parse(link));
after that your Response object (response) will get that file in self and you can simply write the response bytes to a file and that file will be your downloaded file.
as I open file like this:
File file = File('image.jpg')
then we have to send response bytes to this file like this:
file.writeAsBytes(response.bodyBytes);
now you have downloaded a image file successfully.. Congrates.
additional, for example let me show you a sample code to download a image file :
import 'dart:io';
import 'package:http/http.dart';
main(List<String> args) async {
var link =
"https://pps.whatsapp.net/v/t61.24694-
24/72779382_449683642563635_3243701117464346624_n.jpg?ccb=11-
4&oh=23e3bc2ce3f4940a70cb464494bbda76&oe=619B3B8C";
Response response = await get(Uri.parse(link));
File file = File('image.jpg');
file.writeAsBytes(response.bodyBytes);
}
look, this is the code and a file named image.jpg is downloaded at bottom in terminal view is our downloaded image.
screen shot
this is our actual image which we downloaded.
downloaded image
Related
I am trying to send file from Client (Angular) to the NestJS same way like it is working now with Java-springboot API.
I am using POST method in NestJS but, unfortunatelly I am not able to got any data from the body :
here is the code :
#Post('/uploadExportFile')
uploadAttachment(#Req() req: Request, #Body() attachment: ArrayBuffer): any {
console.log(attachment);
return {};
}
content-type is set in header on Client side, I am not sure if I need to set content-types there ? Content type depends on file mimetype it should be (application/pdf/png/jpeg)..not multiform or what I need to do to achieve that attachment object will not return empty {} .
req.body is undefined
What I need to do with that file is to again change it back to Base64 (in angular it is in Base64) but Java API consumes only byte[] so I need to keep that like it is on FE.
any suggestions what is wrong in this "simple" code?
** EDIT **
====↓ EDIT ↓====
Solution: request.body is undefined is:
NestJS use as default body jsonBody, so in that case you have to override for specific routes that you want to use raw-body, and if raw-body is used insted of jsonBody, then the body from request is not undefined and it contain ArrayBuffer.
What you need to do is something like this;
Create rawBody middleware raw-body.middleware.ts
import { Injectable, NestMiddleware } from '#nestjs/common';
import { Request, Response } from 'express';
import * as bodyParser from 'body-parser';
#Injectable()
export class RawBodyMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: () => any) {
bodyParser.raw({type: '*/*'})(req, res, next);
}
}
app.module.ts
export class AppModule implements NestModule {
public configure(consumer: MiddlewareConsumer): void {
consumer
.apply(RawBodyMiddleware)
.forRoutes({
path: '/uploadExportFile',
method: RequestMethod.POST,
})
.apply(JsonBodyMiddleware)
.forRoutes('*');
}
}
and you need to disable bodyparser in main.ts
const app = await NestFactory.create(AppModule, { bodyParser: false })
in new version of NestJS is introduced new option raw-body but I have no possibility to test that https://docs.nestjs.com/faq/raw-body#raw-body
frist thing send the content-type application/x-www-form-urlencoded
and sure you have add UseInterceptors Like FileInterceptor
you can import FileInterceptor
if you need to get buffer try use file.buffer
import {FileInterceptor} from "#nestjs/platform-express";
#Post('upload')
#UseInterceptors(FileInterceptor('file'))
async upload(#Req() request: RequestWithUser, #UploadedFile() file) {
if (!file) {
throw new HttpException('File is required', HttpStatus.BAD_REQUEST);
}
// you have file
return await this.storageService.upload(file, request.user);
}
I've been searching in vain for a simple way of uploading a JSON file to a specific URL but I haven't been able to find one, for Flutter.
I have implemented the code to download a simple JSON file from a specific URL. What I haven't been able to find is how to upload the same file to same location.
Do I need to do the multipart stuff? And I'm not even sure how that works.
EDIT
I'm starting with Map data (Map) and I want to upload it to a server as JSON (text file). This code is specific to binary data. And yes, I'm just writing to a URL, not an endpoint:
Upload(File imageFile) async {
var stream = new
http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
var length = await imageFile.length();
var uri = Uri.parse(uploadURL);
var request = new http.MultipartRequest("POST", uri);
var multipartFile = new http.MultipartFile('file', stream, length,
filename: basename(imageFile.path));
//contentType: new MediaType('image', 'png'));
request.files.add(multipartFile);
var response = await request.send();
print(response.statusCode);
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}
To upload files to an endpoint, you can use http.MultipartRequest - this allows you to upload files with binary content (images, docs, etc.) and files with regular text.
import 'package:http/http.dart' as http;
String url = // your endpoint
var req = http.MultipartRequest('POST', Uri.parse(url));
Then to upload
var request = http.MultipartRequest('POST', Uri.parse(url));
request.files.add(
await http.MultipartFile.fromPath(
'json',
filePath
)
);
var res = await request.send();
I would like to know how can a server side application receive a file (via POST) and then print its contents on the server side.
The most "up to date" related question here was this one: Dart how to upload image
But it is not working anymore (Uncaught Error: type 'String' is not a subtype of type 'HttpBodyFileUpload' of 'fileUploaded').
EDIT:
This is how I send the file (this method is working fine):
import 'dart:html';
import 'dart:async';
HttpRequest request = new HttpRequest();
final _HOST = "127.0.0.1", _PORT = 8123;
Future sendFile(File file) {
var completer = new Completer(); // No need for a Completer. It will be removed.
Uri uri = new Uri(host: _HOST, port: _PORT);
request.open("POST", uri.toString());
var filename = file.name;
final FormData formData = new FormData();
formData.append('file', filename);
request.onLoadEnd.listen((_) {
completer.complete(request.response);
});
request.send(formData);
return completer.future;
}
The server side (I'm stuck here):
void _handlePost(HttpRequest req) {
HttpBodyHandler.processRequest(req).then((body) {
HttpBodyFileUpload fileUploaded = body.body['file'];
print(fileUploaded.content);
});
}
You are appending the filename instead of the Blob (File) to your FormData object. In Dart it looks like there is a special function for appending blobs called appendBlob(name, blob, [filename]).
I need to post a PDF file to a remote REST API, and I can't for the life of me figure it out. No matter what I do, the server responds that I have not yet associated an object with the file parameter. Let's say that I have a PDF called test.pdf. This is what I've been doing so far:
// Using an HttpClientRequest named req
req.headers.contentType = new ContentType('application', 'x-www-form-urlencoded');
StringBuffer sb = new StringBuffer();
String fileData = new File('Test.pdf').readAsStringSync();
sb.write('file=$fileData');
req.write(sb.toString());
return req.close();
Thus far, I've tried virtually every combination and encoding of the data that I write() to the request, but to no avail. I've tried sending it as codeUnits, I've tried encoding it using a UTF8.encode, I've tried encoding it using a Latin1Codec, everything. I'm stumped.
Any help would be greatly appreciated.
You can use MultipartRequest from the http package :
var uri = Uri.parse("http://pub.dartlang.org/packages/create");
var request = new http.MultipartRequest("POST", url);
request.fields['user'] = 'john#doe.com';
request.files.add(new http.MultipartFile.fromFile(
'package',
new File('build/package.tar.gz'),
contentType: new ContentType('application', 'x-tar'));
request.send().then((response) {
if (response.statusCode == 200) print("Uploaded!");
});
Try using the multipart/form-data header rather than x-www-form-urlencoded. This should be used for binary data, also can you show your full req request?
void uploadFile(File file) async {
// string to uri
var uri = Uri.parse("enter here upload URL");
// create multipart request
var request = new http.MultipartRequest("POST", uri);
// if you need more parameters to parse, add those like this. i added "user_id". here this "user_id" is a key of the API request
request.fields["user_id"] = "text";
// multipart that takes file.. here this "idDocumentOne_1" is a key of the API request
MultipartFile multipartFile = await http.MultipartFile.fromPath(
'idDocumentOne_1',
file.path
);
// add file to multipart
request.files.add(multipartFile);
// send request to upload file
await request.send().then((response) async {
// listen for response
response.stream.transform(utf8.decoder).listen((value) {
print(value);
});
}).catchError((e) {
print(e);
});
}
I used file picker to pick file.
Here is the codes for pick file.
Future getPdfAndUpload(int position) async {
File file = await FilePicker.getFile(
type: FileType.custom,
allowedExtensions: ['pdf','docx'],
);
if(file != null) {
setState(() {
file1 = file; //file1 is a global variable which i created
});
}
}
here file_picker flutter library.
I am writing a web server application using Dart.
How do I send an image file through a HttpServer to the browser?
When you receive a request for an image, send a header to state the content type and length, and then the file contents.
import 'dart:io';
void main() {
HttpServer.bind('127.0.0.1', 8080).then((server) {
server.listen((HttpRequest request) {
File image = new File("chicken.jpeg");
image.readAsBytes().then(
(raw){
request.response.headers.set('Content-Type', 'image/jpeg');
request.response.headers.set('Content-Length', raw.length);
request.response.add(raw);
request.response.close();
});
});
});
}