如何在Flutter中将图片上传到服务器?

51

我想上传一张图片,我正在使用 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: )
}

请求的主体和编码部分应该是什么?


1
你应该能够使用来自dart question的相同方法! - German Saprykin
那样做可以解决问题,但是那个答案来自于旧版本的库。 - karan vs
3
request.files.add( new http.MultipartFile.fromBytes( "file", file.readAsBytesSync(), filename: "Photo.jpg", contentType: new MediaType("image", "jpg") ) );//现在已经可以正常工作了。 - karan vs
遇到同样的问题,您能分享解决方案吗? - wil
15个回答

1
我发现了一种在Flutter中轻松上传图像并在服务器上接收的方法。
 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")
})

这种方法对我很有效,而且相比其他方法来说,我觉得它更容易。


1

以下是我的工作代码,基于@TejaDroid's sample,它通过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);
  }

0

我在多个地方查找了相关信息,最终找到了解决方案 -

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

0
如果你想将它作为二进制文件上传。
  static uploadFile(File imageFile) async {
    final response = await http.post(postURL, body: imageFile.readAsBytesSync());
    return json.decode(response.body);
  }

谢谢

0

导入 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) {}
            }
          }

我该如何在我的 .php 文件中接收它? - Santiago Arteaga

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接