如何使用flutter和laravel API上传图片到服务器?

jrcvhitl  于 2022-12-19  发布在  Flutter
关注(0)|答案(3)|浏览(165)

如何使用flutter和Laravel API在服务器上上传图片?我试过使用getx,它返回null。另外,我的pubspec.yaml中有image_picker和image_cropper包

yshpjwxd

yshpjwxd1#

使用File Picker从图库中选择图像

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:file_picker/file_picker.dart';
class ImageScreen extends StatefulWidget {
  ImageScreen();
  @override
  State<ImageScreen> createState() => _ImageScreenState();
}

class _ImageScreenState extends State<ImageScreen> {
  File file;

  Future<File> uploadImage() async {
    FilePickerResult result = await FilePicker.platform.pickFiles();

    if (result != null) {
      setState(() {
        file = File(result.files.single.path);
      });
      print(result.files.single.path);

    } else {
      // User canceled the picker
    }
    return file;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        onTap: () {
          uploadImage();
        },
        child: Container(
          color: Colors.green,
          padding: EdgeInsets.all(5),
          child: Text('Upload Image', style: TextStyle(fontSize: 16, color: Colors.white),)
        ),
      ),
    );
  }
}

使用http.multipartFile将图像上载到服务器

static Future<dynamic> uploadImage({File file}) async {
    try {
      http.MultipartRequest request = new http.MultipartRequest("POST", _uri);
      http.MultipartFile multipartFile = await http.MultipartFile.fromPath('file_name', file.path);
      request.files.add(multipartFile);
      var streamedResponse = await request.send();
      var response = await http.Response.fromStream(streamedResponse);
      if (response.statusCode == 200 ) {
        return jsonDecode(response.body);
      }
    }
    catch (e) {
      return null;
    }
  }
k4emjkb1

k4emjkb12#

final images = <File>[].obs;

使用此方法拾取图像

Future pickImage(ImageSource source) async {
    ImagePicker imagePicker = ImagePicker();
    XFile pickedFile = await imagePicker.pickImage(source: source, imageQuality: 80);
    File imageFile = File(pickedFile.path);
    print(imageFile);
    if (imageFile != null) {
        images.add(imageFile);
    } else {
      Get.showSnackbar(GetSnackBar(message: "Please select an image file"));
    }
  }

用这个上传图片到你指定的url服务器。我用dio上传。你也可以用http

Future<String> uploadImage(File file) async {
        String fileName = file.path.split('/').last;
// you can edit it for your own convenience
        var _queryParameters = {
          'api_token': 'your token if required',
        };

        Uri _uri = 'Your base url'
    
        var formData = FormData.fromMap({
          "file": await MultipartFile.fromFile(file.path, filename: fileName),
        });
        var response = await dio.post(_uri, data: formData);
        print(response.data);
        if (response.data['data'] != false) {
          return response.data['data'];
        } else {
          throw new Exception(response.data['message']);
        }
      }
a7qyws3x

a7qyws3x3#

这对我很有效,所以也许其他人可能也需要它。

uploadImage(imageFile) async {
    var stream = new http.ByteStream(
    DelegatingStream.typed(imageFile.openRead()));
    var length = await imageFile.length();

    var uri = Uri.parse(
    'http://192.168.5.196/ApiFileUploadTest/public/api/uploading-file-api');

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

    request.files.add(multipartFile);
    var response = await request.send();
    print(response.statusCode);
    response.stream.transform(utf8.decoder).listen((value) {
    print(value);
    });
    }

相关问题