上传图片/文件到 Strapi (Flutter Web)

Die*_*vel 5 form-data flutter strapi dio flutter-http

我正在尝试通过 Flutter Web 将图像上传到 Strapi。我知道(从此链接)我需要使用 FormData 来做到这一点。我研究了很多方法来做到这一点,我偶然发现了Dio,当然还有Http

两种解决方案都给了我错误: Unsupported operation: MultipartFile is only supported where dart:io is available.

我试过这个代码:

var request = new http.MultipartRequest("POST", Uri.parse(url));
    request.files.add(
      await http.MultipartFile.fromPath(
        "files",
        imageFilePath,
      ),
    );
    request.send().then((response) {
      if (response.statusCode == 200) print("Uploaded!");
      print(response.statusCode);
    }).catchError((e) => print(e));
Run Code Online (Sandbox Code Playgroud)

正如这里所建议的。

当我使用MultipartFile.fromBytes(...).

我只是想上传一个文件,因此我认为我的身体应该只包含 FormData ,正如Strapi 的文档中files提到的那样

Die*_*vel 6

所以,我在 Flutter Discord 上搜索了一些帮助,我发现我的问题发生是因为 Flutter Web 无法使用'dart:io',而使用'dart:html'会带走所有 Flutter 平台的使用。

我最终使用了这个进口:

import 'dart:convert';
import 'dart:typed_data';
import 'package:image_picker/image_picker.dart';
import 'package:http/http.dart' as http;
import 'package:http_parser/http_parser.dart';
import 'package:path/path.dart';
import 'package:async/async.dart';
Run Code Online (Sandbox Code Playgroud)

这是我创建和工作的功能:

 Future<bool> uploadImage(
    String imageFilePath,
    Uint8List imageBytes,
  ) async {
    String url = SERVERURL + "/uploadRoute";
    PickedFile imageFile = PickedFile(imageFilePath);
    var stream =
        new http.ByteStream(DelegatingStream.typed(imageFile.openRead()));

    var uri = Uri.parse(url);
    int length = imageBytes.length;
    var request = new http.MultipartRequest("POST", uri);
    var multipartFile = new http.MultipartFile('files', stream, length,
        filename: basename(imageFile.path),
        contentType: MediaType('image', 'png'));

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

我在使用Strapi 时遇到了这个问题,这个解决方案很有魅力。


归档时间:

查看次数:

2071 次

最近记录:

4 年,10 月 前