繁体   English   中英

如何在 flutter 中使用 file_picker package 上传文件

[英]How to upload a file using file_picker package in flutter

我需要通过 EmailJS 将文件从我的 flutter 应用程序发送到我的 email。 我在 EmailJS 中创建了一个模板,还在 flutter 上创建了一个表单。我正在将所有文本字段和保管箱数据发送到我的 email。我如何使用 file_picker 发送选取的图像。

这里我定义了变量

final response = await http.post(
url,
headers: {
  'origin': 'http://localhost',
  'Content-Type': 'application/json',
},
body:json.encode({
  'service_id': serviceId,
  'template_id': templateId,
  'user_id': userId,
  'template_params':{
    'user_accident_number': accident_number,
    'user_contact_name': contact_name,
    'user_mobile_number': mobile_number,
    'user_email': email,

    'user_car_registration': car_registration,
    'user_driving_license': driving_license,
    'user_police report': police_report,
    'user_qatar_id': qatar_id,

    'user_city': city,
    //'user_service': service,
  }
}),


);
  print(response.body);
}
class CustomForm extends StatefulWidget {
  const CustomForm({Key? key}) : super(key: key);
  @override
  _CustomFormState createState() => _CustomFormState();
}
class _CustomFormState extends State<CustomForm> {
  final _formKey = GlobalKey<FormState>();
  final items = ['Select', 'Doha', 'Al Khor', 'Al Wakrah'];
  //String? value;
  String dropdownValue = 'Select';
  final dropdownValueKey = GlobalKey<FormState>();
  final controllerAccidentNumber = TextEditingController();
  final controllerContactName = TextEditingController();
  final controllerMobileNumber = TextEditingController();
  final controllerEmail = TextEditingController();
  final snackBar = SnackBar(
    content: const Text(
        'Successfully Sent'
    ),
  );
  var carRegistration = 'No Files Selected';
  var drivingLicense = 'No Files Selected';
  var policeReport = 'No Files Selected';
  var qatarId = 'No Files Selected';

在这里我选择图像

Padding(
          padding: EdgeInsets.fromLTRB(20, 10, 20, 10),
          child: RaisedButton(
            elevation: 0,
            onPressed: () async{
              final result = await FilePicker.platform.pickFiles();
              if(result == null) return;
              final PlatformFile file = result.files.first;
              setState(() {
                qatarId = file.name;
              });
              openFile(file);
            },
            color: Colors.white,
            shape: RoundedRectangleBorder(
              side: BorderSide(
                color: Colors.green,
                width: 1),
              borderRadius: BorderRadius.all(Radius.circular(0),
              ),
            ),
            child: Padding(
              padding: EdgeInsets.fromLTRB(10, 10, 10, 10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Text(
                    'Qatar ID',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.normal,
                      color: Colors.green,
                    ),
                  ),
                  Icon(
                    Icons.upload_sharp,
                    color: Colors.green,
                  )
                ],
              ),
            ),
          ),
        ),

我在这里发送数据。

onPressed: () => [
                if (_formKey.currentState!.validate()) {
                   sendEmail(
                     accident_number: controllerAccidentNumber.text,
                     contact_name: controllerContactName.text,
                     mobile_number: controllerMobileNumber.text,
                     email: controllerEmail.text,
                     city: dropdownValue.toString(),
                     car_registration: carRegistration,
                     driving_license: drivingLicense,
                     police_report: policeReport,
                     qatar_id: qatarId,
                   ),
                  controllerAccidentNumber.clear(),
                  controllerContactName.clear(),
                  controllerMobileNumber.clear(),
                  controllerEmail.clear(),
                  setState(() {
                    carRegistration = '';
                    drivingLicense = '';
                    policeReport = '';
                    qatarId = '';
                  }),
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text(
                          'Successfully sent'
                      ),
                    ),
                  ),
                },
              ],

另外,我在 email 中获取图像名称。如何获取图像。

要在post方法中包含文件,您需要使用 multipart

对于多部分 POST 请求,除了常规文本值之外,您还可以包含具有二进制内容(图像、各种文档等)的文件。

 var request = http.MultipartRequest('POST', Uri.parse(url));
  request.files.add(
    await http.MultipartFile.fromPath(
      'picture',
      filename
    )
  );
//normal text 
request.fields['key'] = 'value';
  var res = await request.send();

你可以在这里这里阅读更多

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM