0

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);
   });
}
JustLearningAgain
  • 2,227
  • 4
  • 34
  • 50
  • If you need multipart depends on what your server expects. If it is form handling, than it might. Normally you can just use a POST request. Similar to GET explained in https://flutter.io/docs/cookbook/networking/fetch-data there should be enough examples here on Stackoverflow for Dart or Flutter – Günter Zöchbauer Jan 23 '19 at 16:07
  • Where are you uploading? Is there api that accepts json format already? If yes then api will specify what kind of request it except. Most probably it will be http.post. Or do you also need to build a server-side api too that will accept a json data from your flutter mobile app (you can do one with dart that accepts and stores json to server pretty easily)? – Ski Jan 23 '19 at 16:33
  • https://stackoverflow.com/a/49645074 – Shyju M Jan 23 '19 at 17:06
  • I think I can figure it out from here but I'd like to put in the code for the answer so that future newbs have something to look at that answers this question specifically. – JustLearningAgain Jan 23 '19 at 18:16
  • 1
    Still can't figure it out. I see code on uploading a bitmap, but nothing on uploading a json file to a specified URL. – JustLearningAgain Jan 24 '19 at 04:01

1 Answers1

0

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();
Omatt
  • 8,564
  • 2
  • 42
  • 144