【问题标题】:Upload Image to Server in flutter将图像上传到服务器
【发布时间】:2022-09-26 13:27:33
【问题描述】:

我最近开始颤抖,我想在我的 php 服务器上上传图片。
我用过 image_picker: ^0.8.5+3http: ^0.13.5
图像选择器工作正常,但点击上传图片到 php 服务器后, 我正在尝试捕获错误:\“转换为 Base64 时出错\”:(
这是 main.dart :

import \'package:flutter/material.dart\';
import \'dart:io\';
import \'dart:convert\';
import \'package:http/http.dart\' as http;
import \'package:image_picker/image_picker.dart\';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: \'Image Upload\',
      theme: ThemeData(
        primarySwatch: Colors.indigo,
      ),
      home: const ImageUpload(),
    );
  }
}


class ImageUpload extends StatefulWidget {
  const ImageUpload({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _ImageUpload();
  }
}

class _ImageUpload extends State<ImageUpload> {
  final ImagePicker _picker = ImagePicker();
  File? uploadimage;

  Future<void> chooseImage() async {
    var choosedimage = await _picker.pickImage(source: ImageSource.gallery);
    setState(() {
      uploadimage = File(choosedimage!.path);
    });
  }

  Future<void> uploadImage() async {
    var uploadurl = Uri.parse(\'http://192.168.1.9/flutter/uploadimage.php\');
    try {
      List<int> imageBytes = uploadimage!.readAsBytesSync();
      print(imageBytes);
      String baseimage = base64Encode(imageBytes);
      var response = await http.post(uploadurl, body: {
        \'image\': baseimage,
      });
      if (response.statusCode == 200) {
        var jsondata = json.decode(response.body);
        if (jsondata[\"error\"]) {
          print(jsondata[\"msg\"]);
        } else {
          print(\"Upload successful\");
        }
      } else {
        print(\"Error during connection to server\");
      }
    } catch (e) {
      print(\"Error during converting to Base64\");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Center(
          child: Text(\"Upload Image to Server\"),
        ),
        backgroundColor: Colors.deepOrangeAccent,
      ),
      body: Container(
        height: 300,
        alignment: Alignment.center,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
                child: uploadimage == null
                    ? Container()
                    : SizedBox(height: 150, child: Image.file(uploadimage!))),
            Container(
                child: uploadimage == null
                    ? Container()
                    : ElevatedButton.icon(
                        onPressed: () {
                          uploadImage();
                        },
                        icon: const Icon(Icons.file_upload),
                        label: const Text(\"UPLOAD IMAGE\"),
                      )),
            ElevatedButton.icon(
              onPressed: () {
                chooseImage();
              },
              icon: const Icon(Icons.folder_open),
              label: const Text(\"CHOOSE IMAGE\"),
            )
          ],
        ),
      ),
    );
  }
}


和我的上传图片.php在 xampp 上运行的文件:

<?php 
$return[\"error\"] = false;
$return[\"msg\"] = \"\";
if(isset($_POST[\"image\"])){
    $base64_string = $_POST[\"image\"];
    $outputfile = \"uploads/image.jpg\" ;
    $filehandler = fopen($outputfile, \'wb\' ); 
    fwrite($filehandler, base64_decode($base64_string));
    fclose($filehandler); 
}else{
    $return[\"error\"] = true;
    $return[\"msg\"] =  \"No image is submited.\";
}

header(\'Content-Type: application/json\');
echo json_encode($return);
?>

任何想法或更好的方法?

  • 你能在你的捕获中打印异常吗

标签: php flutter dart


【解决方案1】:
var response = await http.post(uploadurl,
     body: {
        'image': baseimage,
      });

对此

import 'dart:convert';

...
var response = await http.post(uploadurl, 
   body: jsonEncode({
        'image': baseimage,
      })
);

这是帮助您调试的提示

catch (e) {
  // print the error instead.
  //so you know what is the issue
   print("Error:  $e");
}

【讨论】:

  • 现在我得到“我/颤振(1224):没有提交图像。”我认为php代码可能有问题。身份证
【解决方案2】:

请尝试这种方式


void uploadImage(File imageFile,Uri uri){

      final ByteStream stream =
          http.ByteStream(Stream.castFrom(imageFile.openRead()));
      final int length = await imageFile.length();



      final request = http.MultipartRequest('POST', uri);
      final multipartFile = http.MultipartFile(
          'file', stream, length,
          filename: basename(imageFile.path));


      request.files.add(multipartFile);
      final StreamedResponse response = await request.send();

}

【讨论】:

  • 这有点模棱两可。我不知道把它放在哪里:)
  • 更新了答案。现在检查
猜你喜欢
  • 2017-06-22
  • 2013-12-17
  • 2014-03-21
  • 2017-05-31
  • 2013-11-02
  • 2014-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多