繁体   English   中英

使用MultiPartRequest上传文件在flutter web

[英]Using MultiPartRequest to upload file in flutter web

所以我目前正在尝试将文件选择器中的图像发送到具有文件输入的 api,这是 postman 显示,事实是,我已经尝试过其他帖子中的多种方式,但没有一个适用于我,这是我从 web 浏览器控制台得到的错误,这是我尝试使用的代码:

var postUri = Uri.parse(constanta.getMyid());
                    http.MultipartRequest request = new http.MultipartRequest("POST", postUri);
                    http.MultipartFile multipartFile = await http.MultipartFile.fromBytes(
                        'data', image);
                    request.files.add(multipartFile);
                    http.StreamedResponse response = await request.send();
                    print(response.statusCode);

我认为主要问题不是 CORS,因为 api 日志表明已收到请求,但没有文件附加到该请求。

附加说明:我已经从客户端尝试了所有方法,但我无法打开/编辑后端,因为它是第三方 api(不归我所有)。

正如我所见,您的错误主要问题首先是您的服务器拒绝了数据,因为服务器不允许您上传文件并抛出您必须首先解决的跨域访问,然后您应该尝试。

如果你的 postman 可以上传图片到服务器,那是因为 postmen 本身可以解决 Cross-Origin Acess Error,所以这里是 node.js 的解决方案

如果您的后端在 node.js 中,您可以将以下代码注入到您的中间件中。

app.use((req, res, next) => {

    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'XMLHttpRequest,Origin,X-Requested-With,Content-Type,Accept,Authorization');
    if (req.method === 'OPTIONS') {
        res.header('Access-Control-Allow-Methods', 'PUT,POST,PATCH,DELETE,GET');
        return res.status(200).json({});
    }
    next();
});

或者您可以使用 localhost 作为后端服务器。

暂无
暂无

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

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