Flutter 如何使用flatter将图像上传到服务器API

Flutter 如何使用flatter将图像上传到服务器API,flutter,dart,Flutter,Dart,我对颤振开发还不熟悉。我的问题是,我试图上传的形象,但我不断得到失败的请求 这段代码就是我将其与服务器API连接的地方,服务器API将从Flatter接收图像文件。字符串附件,由位于另一页的createIncident函数传递的图像路径组成 Future<IncidentCreateResponse> createIncident( String requesterName, String requesterEmail,

我对颤振开发还不熟悉。我的问题是,我试图上传的形象,但我不断得到失败的请求

这段代码就是我将其与服务器API连接的地方,服务器API将从Flatter接收图像文件。字符串附件,由位于另一页的createIncident函数传递的图像路径组成

Future<IncidentCreateResponse> createIncident( String requesterName, String requesterEmail, 
                                              String requesterMobile, String attachment, String title,
                                              String tags, String body, String teamId,
                                              String address )  async {
    IncidentCreateResponse incidentCreateResponse;
    var url = GlobalConfig.API_BASE_HANDESK + GlobalConfig.API_INCIDENT_CREATE_TICKETS;
    var token = Auth().loginSession.accessToken;
    var postBody = new Map<String, dynamic>();
    postBody["requester_name"] = requesterName;
    postBody["requester_email"] = requesterEmail;
    postBody["requester_mobile_no"] = requesterMobile;
    postBody["attachment"] = attachment;
    postBody["title"] = title;
    postBody["tags"] = tags;
    postBody["body"] = body;
    postBody["teamId"] = teamId;
    postBody["address"] = address;

    // Await the http get response, then decode the json-formatted responce.
    var response = await http.post(
        url,
        body: postBody,
        headers: {
          'X-APP-ID': GlobalConfig.APP_ID,
          "Accept": "application/json; charset=UTF-8",
          // "Content-Type": "application/x-www-form-urlencoded",
          HttpHeaders.authorizationHeader: 'Bearer $token',
          'token': GlobalConfig.API_INCIDENT_REPORT_TOKEN  
        }
      );
    if ((response.statusCode == 200) || (response.statusCode == 201)) {
      print(response.body);
      var data = json.decode(response.body);

      incidentCreateResponse = IncidentCreateResponse.fromJson(data['data']);
    } else {
      print("createIncident failed with status: ${response.statusCode}.");

      incidentCreateResponse = null;
    }

    return incidentCreateResponse;
  }
这是我将附件字符串传递给HTTP响应的代码

this.incidentService.createIncident(
     Auth().loginSession.name, 
     Auth().loginSession.email, 
     Auth().loginSession.mobile_no, 
     this.attachment,
     this._titleController.text, 
     this._tags, 
     this._contentController.text, 
     this._teamId,
     this._addressController.text
).then((IncidentCreateResponse res) {
     if (res != null) {
        print('Ticket Id: ' + res.id);
        // Navigator.pop(context);
        this._successSubmittionDialog(context);
     } else {
        this._errorSubmittionDialog(context);
     }
}

您可以使用multipart或base64编码上传图像

要使用multipart上载图像,请访问

对于使用base64 Encode上载图像,您可以签出


我建议使用多部分图像上传,因为当您的图像或文件较大时,它甚至是可靠的。

希望这能帮助您

创建一个函数,在拾取或单击图像后上载图像,如

Future<ResponseModel> uploadPhoto(
  String _token,
  File _image,
  String _path,
) async {
  Dio dio = new Dio();
  FormData _formdata = new FormData();
  _formdata.add("photo", new UploadFileInfo(_image, _path));
  final response = await dio.post(
    baseUrl + '/image/upload',
    data: _formdata,
    options: Options(
      method: 'POST',
      headers: {
        authTokenHeader: _token,
      },
      responseType: ResponseType.json,
    ),
  );
  if (response.statusCode == 200 || response.statusCode == 500) {
    return ResponseModel.fromJson(json.decode(response.toString()));
  } else {
    throw Exception('Failed to upload!');
  }
}
我已经使用了Dio的任务,你可以找到更多关于Dio的细节

将其添加到包的pubspec.yaml文件:

dependencies:
  dio: ^3.0.5
然后将其导入Dart代码,您可以使用:

import 'package:dio/dio.dart';

要使用多部分API上载图像,请使用以下代码

在项目的
pubspec.yaml
文件中添加此库
dio

dio: ^3.0.5
然后在你的课堂上导入这个

import 'package:dio/dio.dart';
在类中声明此变量,如
State

然后使用此方法上载文件

Future<dynamic> _uploadFile() async {
    try {
      Options options = Options(
          //contentType: ContentType.parse('application/json'), // only for json type api
          );

      var directory = await getExternalStorageDirectory(); // directory path
      final path = await directory.path; // path of the directory
      Response response = await dio.post('/update_profile',
          data: FormData.from({
            "param_key": "value",
            "param2_key": "value",
            "param3_key": "value",
            "profile_pic_param_key": UploadFileInfo(File("$path/pic.jpg"), "pic.jpg"),

          }),
          options: options);
      setState(() {
        isLoading = false;
      });
      if (response.statusCode == 200 || response.statusCode == 201) {
        var responseJson = json.decode(response.data);
        return responseJson;
      } else if (response.statusCode == 401) {
        print(' response code 401');
        throw Exception("Incorrect Email/Password");
      } else
        throw Exception('Authentication Error');
    } on DioError catch (exception) {
      if (exception == null ||
          exception.toString().contains('SocketException')) {
        throw Exception("Network Error");
      } else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
          exception.type == DioErrorType.CONNECT_TIMEOUT) {
        throw Exception(
            "Could'nt connect, please ensure you have a stable network.");
      } else {
        return null;
      }
    }
  }
Future\u uploadFile()异步{
试一试{
选项=选项(
//contentType:contentType.parse('application/json'),//仅适用于json类型api
);
var directory=await getExternalStorageDirectory();//目录路径
final path=wait directory.path;//目录的路径
Response Response=wait dio.post(“/update_profile”,
数据:FormData.from({
“参数键”:“值”,
“参数2_键”:“值”,
“参数3_键”:“值”,
“profile_pic_param_key”:UploadFileInfo(文件(“$path/pic.jpg”),“pic.jpg”),
}),
选择:选择);
设置状态(){
isLoading=false;
});
if(response.statusCode==200 | | response.statusCode==201){
var responseJson=json.decode(response.data);
返回响应;
}else if(response.statusCode==401){
打印(‘响应代码401’);
抛出异常(“错误的电子邮件/密码”);
}否则
抛出异常(“身份验证错误”);
}关于错误捕获(异常){
如果(异常==null)||
exception.toString()包含('SocketException')){
抛出异常(“网络错误”);
}else if(exception.type==DioErrorType.RECEIVE\u超时||
exception.type==DioErrorType.CONNECT\u超时){
抛出异常(
“无法连接,请确保您有一个稳定的网络。”);
}否则{
返回null;
}
}
}

在这里检查我的答案,这可能会帮助您,非常感谢。我将测试您提供的解决方案。我认为这不是重复,因为他的要求和我的有点不同。好的,你可以通过我的解决方案上传单个和多个图像。我在“UploadFileInfo”中遇到错误。我错过什么了吗?
import 'package:dio/dio.dart';
static var uri = "BASE_URL_HERE";
  static BaseOptions options = BaseOptions(
      baseUrl: uri,
      responseType: ResponseType.plain,
      connectTimeout: 30000,
      receiveTimeout: 30000,
      validateStatus: (code) {
        if (code >= 200) {
          return true;
        }
      });
  static Dio dio = Dio(options);
Future<dynamic> _uploadFile() async {
    try {
      Options options = Options(
          //contentType: ContentType.parse('application/json'), // only for json type api
          );

      var directory = await getExternalStorageDirectory(); // directory path
      final path = await directory.path; // path of the directory
      Response response = await dio.post('/update_profile',
          data: FormData.from({
            "param_key": "value",
            "param2_key": "value",
            "param3_key": "value",
            "profile_pic_param_key": UploadFileInfo(File("$path/pic.jpg"), "pic.jpg"),

          }),
          options: options);
      setState(() {
        isLoading = false;
      });
      if (response.statusCode == 200 || response.statusCode == 201) {
        var responseJson = json.decode(response.data);
        return responseJson;
      } else if (response.statusCode == 401) {
        print(' response code 401');
        throw Exception("Incorrect Email/Password");
      } else
        throw Exception('Authentication Error');
    } on DioError catch (exception) {
      if (exception == null ||
          exception.toString().contains('SocketException')) {
        throw Exception("Network Error");
      } else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
          exception.type == DioErrorType.CONNECT_TIMEOUT) {
        throw Exception(
            "Could'nt connect, please ensure you have a stable network.");
      } else {
        return null;
      }
    }
  }