如何将图像上传到扑朔迷离的服务器



我想上传图像,我正在使用http.client((提出请求,

static uploadImage(String id, File file) {
  var httpClient = createHttpClient();
  Map<String, String> headers = new Map<String, String>();
  headers.putIfAbsent("Authorization", () => "---");
  headers.putIfAbsent("Content-Type", () => "application/json");
  var body=new List();
  body.add(id.)
  httpClient.post(URL_UPLOADIMAGE,headers: headers,body: ,encoding: )
}

该请求的身体应该是什么?

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);
      });
    }

名称空间:

import 'package:path/path.dart';
import 'package:async/async.dart';
import 'dart:io';
import 'package:http/http.dart' as http;

最简单的方法是使用http库,

import 'dart:io';
import 'package:http/http.dart' as http;
_asyncFileUpload(String text, File file) async{
   //create multipart request for POST or PATCH method
   var request = http.MultipartRequest("POST", Uri.parse("<url>"));
   //add text fields
   request.fields["text_field"] = text;
   //create multipart using filepath, string or bytes
   var pic = await http.MultipartFile.fromPath("file_field", file.path);
   //add multipart to request
   request.files.add(pic);
   var response = await request.send();
   //Get the response from the server
   var responseData = await response.stream.toBytes();
   var responseString = String.fromCharCodes(responseData);
   print(responseString);
}

submitForm()方法中检查身体。

File _image;
Future cameraImage() async {
  var image = await ImagePicker.pickImage(
    source: ImageSource.camera,
    maxHeight: 240.0,
    maxWidth: 240.0,
  );
  setState(() {
    _image = image;
  });
}
submitForm() async {
  final response = await http.post(
    uri,
    headers: {
      AuthUtils.AUTH_HEADER: _authToken
    },
    body: {
      'user_id': userId
      'photo': _image != null ? 'data:image/png;base64,' +
          base64Encode(_image.readAsBytesSync()) : '',
    },
  );
  final responseJson = json.decode(response.body);
  print(responseJson);
}

我已经尝试了以上所有内容,但没有一个对我上传到服务器的文件。

深入搜索后,我得到了一个与Dio相同的插件。

以下代码将文件上传到服务器。

uploadFileFromDio(UserProfile userProfile, File photoFile) async {
    var dio = new Dio();
    dio.options.baseUrl = url;
    dio.options.connectTimeout = 5000; //5s
    dio.options.receiveTimeout = 5000;
    dio.options.headers = <Header Json>;
    FormData formData = new FormData();
    formData.add("user_id", userProfile.userId);
    formData.add("name", userProfile.name);
    formData.add("email", userProfile.email);
    if (photoFile != null &&
        photoFile.path != null &&
        photoFile.path.isNotEmpty) {
      // Create a FormData
      String fileName = basename(photoFile.path);
      print("File Name : $fileName");
      print("File Size : ${photoFile.lengthSync()}");
      formData.add("user_picture", new UploadFileInfo(photoFile, fileName));
    }
    var response = await dio.post("user/manage_profile",
        data: formData,
        options: Options(
            method: 'POST',
            responseType: ResponseType.PLAIN // or ResponseType.JSON
            ));
    print("Response status: ${response.statusCode}");
    print("Response data: ${response.data}");
  }

我找到了一个工作示例,而无需使用任何外部插件, 仅使用

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

代码

var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));
    // get file length
    var length = await imageFile.length(); //imageFile is your image file
    Map<String, String> headers = {
      "Accept": "application/json",
      "Authorization": "Bearer " + token
    }; // ignore this headers if there is no authentication
    // string to uri
    var uri = Uri.parse(Constants.BASE_URL + "api endpoint here");
    // create multipart request
    var request = new http.MultipartRequest("POST", uri);
  // multipart that takes file
    var multipartFileSign = new http.MultipartFile('profile_pic', stream, length,
        filename: basename(imageFile.path));
    // add file to multipart
    request.files.add(multipartFileSign);
    //add headers
    request.headers.addAll(headers);
    //adding params
    request.fields['loginId'] = '12';
    request.fields['firstName'] = 'abc';
   // request.fields['lastName'] = 'efg';
    // send
    var response = await request.send();
    print(response.statusCode);
    // listen for response
    response.stream.transform(utf8.decoder).listen((value) {
      print(value);
    });

请尝试以下解决方案

Future<String> uploadImageHTTP(file, url) async {
  var request = http.MultipartRequest('POST', Uri.parse(url));
  request.files.add(await http.MultipartFile.fromPath('picture', file.path));
  var res = await request.send();
  return res.reasonPhrase;
}

考虑使用Flutter's Firebase Storage插件 - 它的功能可用于将大型图像文件上传到移动连接上。

我写了插件,贡献和反馈!

首先,从画廊或相机中选择您的图像

File _image;
Future _getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
setState(() {
_image = image;
});
}

现在在按钮或_getImage((函数内调用以下函数。在文件中,我将上传其他字段,也可以在SaveInattendance((

中看到

不要忘记导入软件包:

import 'package:dio/dio.dart';
import 'package:path/path.dart';
Future saveInAttendance( BuildContext context,String entryType,String mode) async {
        Dio dio = new Dio();
        FormData formData = new FormData(); // just like JS
        formData.add("inimageFile", new UploadFileInfo(_image, basename(_image.path)));
        formData.add("compID",2);
        formData.add("company_id",2);
        formData.add("EntryType", entryType);
        formData.add("emp_code", 5);
        formData.add("Mode",mode);
        formData.add("location",""+_startLocation.latitude.toString()+"-"+_startLocation.longitude.toString());
        dio.post(url_save_attendance, data: formData, options: Options(
            method: 'POST',
            responseType: ResponseType.json // or ResponseType.JSON
        ))
            .then((r) {
          setState(() {
            var data = json.decode(r.toString());
            if(data["apiMessage"].contains('Saved')){
              warningAlert("Attendance Saved", "Your attendance saved Successfully",context);
            }
          });
        }).catchError(print);
      }

有关更多信息,您可以在此处访问

从请求中获取身体而不是

response.stream.transform(utf8.decoder).listen((value) {
    print(value);
  });

我使用:

String body=await response.stream.bytesToString()

我在下面的工作代码,基于 @tejadroid的样本,它通过AWS Gateway API上传一个图像,并在后面具有Lambda功能,将图像存储到S3中。

uploadImageWithhttp(File imageFile, int serialno) async {
    var postBody= {
        'username': 'test@gmail.com',  
        "productid": "1000123",             //TODO
        "imageno": serialno.toString(), 
        'image': imageFile != null ? base64Encode(imageFile.readAsBytesSync()) : '',
    };
    final response = await http.post(
      constAWSAPIGateway_UploadImage[CONST_API_STAGE],
      headers: {
        //AuthUtils.AUTH_HEADER: _authToken
        'Content-Type' : 'application/json',
      },
      body: json.encode(postBody),
    );
    final responseJson = json.decode(response.body);
    print(responseJson);
  }
updateProfile() async {
        try {
          if (_formKey.currentState.validate()) {
            _formKey.currentState.save();
            var dio = new Dio();
            var formData = FormData.fromMap({
              'name': name,
              'con_person_name': concernedPersonName,
              'email': email,
              'phone': phoneNumber,
              'password': password,
              'token': token,
              'user_type': '3',
              'license_no': licenceNumber,
              'gstno': gstNumber,
              'address': address,
              'hospital_id': '102'
              'image': await MultipartFile.fromFile(_image?.path,
            filename: _image.path.split('/').last ?? 'image.jpeg'),
           
            });
            var response = await dio.post('$SERVER_ADDRESS/api/doctorregister',
                data: formData);
            print(response.statusCode);
            print(response.data);
          }
        } catch (error) {
          print(error.toString());
        }
      }

我找到了一种简单的方法来将图像上传到扑朔迷离,甚至在服务器上接收。

颤音:

 MaterialButton(
                color: Colors.blue,
                child: Text(
                  "Pick Image from Camera",
                  style: TextStyle(
                      color: Colors.white70, fontWeight: FontWeight.bold),
                ),
                onPressed: () async {
                  final XFile? photo =
                      await _picker.pickImage(source: ImageSource.camera);
                  print(photo!.path);
                
                  await uploadImage(photo.path);
                },
              ),  

'uploadimage'函数:

uploadImage(String filepath) async {
    var url = 'http://192.168.75.57:4000/upload';
    var request = http.MultipartRequest('POST', Uri.parse(url));
    request.files.add(await http.MultipartFile.fromPath("img", filepath));
    request.fields['_id'] = "abcdef";
    request.headers.addAll({
      "Content-type": "multipart/form-data",
    });
    var response = request.send();
    return response;
  }

在服务器端:( nodejs(为此,首先安装multer(npm install multer(

const multer = require('multer');
const path = require('path')
const storage = multer.diskStorage({
    destination: './uploads',
    filename: (req, file, cb) => {
        cb(null, (new Date()).getTime().toString() + ".jpg");
    },
});
const fileFilter = (req, file, cb) => {
    if (file.mimetype == "image/jpeg" || file.mimetype == "image/png") {
        cb(null, true);
    } else {
        cb(null, false);
    }
};
const upload = multer({
    storage: storage,
    limits: {
        fileSize: 1024 * 1024 * 6,
    },
    fileFilter: fileFilter,
});

最后,兑现了Flutter应用程序的请求:(在router.js中(

router.post('/upload', upload.single("img"), function (req, res) {
    console.log("hit")
    console.log(req.body._id)
    res.send("ok")
})

这种方法对我有用,我发现它比其他方法相对容易。

导入dio, image_picker

    Future _onGalleryPressed() async {
            Future<File> image = ImagePicker.pickImage(source: ImageSource.gallery);
            setState(() {
              this._imageFile = image;
            });
            File img = await image;
            Navigator.of(context).pop();
            if (img != null) {
              //API CALL
              try {
                FormData formData = new FormData.from({"file": path});
                var url = backendUrl + "/upload-image";
                var token = await _getMobileToken();
                Map<String, String> headers = {
                  'Authorization': 'Bearer $token',
                  "Content-Type": "multipart/form-data",
                  "X-Requested-With": "XMLHttpRequest"
                };
                await dio.post(url,
                  data: formData,
                  options: Options(
                      method: 'POST',
                      headers: headers,
                      responseType: ResponseType.json // or ResponseType.JSON
                      ));
                Navigator.pop(context);
              } catch (e) {}
            }
          }

如果要将其上传为二进制文件。

  static uploadFile(File imageFile) async {
    final response = await http.post(postURL, body: imageFile.readAsBytesSync());
    return json.decode(response.body);
  }

谢谢

我在多个地方检查了它,最终我找到了一个解决方案 -

                    var objToSend = {
                          "file": await MultipartFile.fromFile(
                                file.path,
                                filename: filename,
                             ),
                    };
                    FormData formData = FormData.fromMap(objToSend);
                   
                    print(formData.files.toString());
                    Dio dio = new Dio();
                    await dio
                        .post(_toSend,
                            data: formData,
                            options: Options(
                               method: 'POST',
                               headers: <String, String>{
                                  "Content-Type": "application/json",
                                  "Access-Control-Allow-Origin": "*",
                                  "Authorization": 'Bearer ' + token
                                 },
                            ))
                        .whenComplete(() {
                             print('uploaded');
                         }).catchError((onError) {
                             print('failed');
                         });

相关内容

  • 没有找到相关文章

最新更新