当前位置: 首页 > 工具软件 > URI.Dart > 使用案例 >

Flutter 文件上传 (基于 http.dart)

贲培
2023-12-01

前言  Flutter 文件/图片  上传

使用 Flutter框架   基于 http.dart 网络库  ImagePicker.pickImage 进行的 App开发:

今天开发过程中 需要上传 图片:看了下官方文档竟然没有介绍的!!!

后来 google 搜索到了在这里记录下:

参考了这位大兄弟

这三种方式的选型   需要和你后台上传方式对应上,否则就没办法上传成功!自然就是报 500,我这里选择的是三种

Flutter 基于http 库 上传文件的几种方式:

  • http.MultipartFile
    (String filename, String url) async {
      var request = http.MultipartRequest('POST', Uri.parse(url));
      request.files.add(
        http.MultipartFile(
          'picture',
          File(filename).readAsBytes().asStream(),
          File(filename).lengthSync(),
          filename: filename.split("/").last
        )
      );
      var res = await request.send();
    }
  • http.MultipartFile.fromBytes
    (String filename, String url) async {
      var request = http.MultipartRequest('POST', Uri.parse(url));
      request.files.add(
        http.MultipartFile.fromBytes(
          'picture',
          File(filename).readAsBytesSync(),
          filename: filename.split("/").last
        )
      );
      var res = await request.send();
    }
  • http.MultipartFile.fromPath
    (String filename, String url) async {
      var request = http.MultipartRequest('POST', Uri.parse(url));
      request.files.add(
        await http.MultipartFile.fromPath(
          'picture',
          filename
        )
      );
      var res = await request.send();
    }

代码:

import 'package:http/http.dart' as http;
import 'dart:convert' as convert;
  

Future<ResponseBase> upLoadFiles(
      {required String pathCode, required String filePath}) async {
    try {
      AppOverlay().showLoading();
      Uri url = Uri.https(AppHost.hostFile, 'Images/ImageSingleUpload');
      http.MultipartRequest request = http.MultipartRequest('POST', url);
      request.fields['pathCode'] = pathCode;
      http.MultipartFile multipartFile =
          await http.MultipartFile.fromPath("image", filePath);
      request.files.add(multipartFile);

      http.StreamedResponse response = await request.send();
      if (response.statusCode == 200) {
        //这里返回值用到了Stream回调
        String res = await response.stream.bytesToString();
        Map<String, dynamic> jsonResponse =
            convert.jsonDecode(res) as Map<String, dynamic>;
        ResponseBase _responseBase = ResponseBase(
          errorCode: jsonResponse['errorCode'],
          action: jsonResponse['action'],
          message: jsonResponse['message'],
          value: jsonResponse['value'],
          success: jsonResponse['success'],
        );
        return _responseBase;
      } else {
        return ResponseBase(
          errorCode: response.statusCode,
          action: 0,
          message: '上传文件失败 请稍后再试 ${response.statusCode}',
          success: false,
          value: {'error get'},
        );
      }
    } catch (exception) {
      AppScreen.showToast('上传文件失败 请稍后再试 ${exception.toString()}');
      return ResponseBase(
        errorCode: -100,
        action: 0,
        message: '网络异常 请稍后再试 -100',
        success: false,
        value: {'error get': exception.toString()},
      );
    } finally {
      AppOverlay().hideLoading();
    }
  }

 类似资料: