简体   繁体   English

使用MultiPartRequest上传文件在flutter web

[英]Using MultiPartRequest to upload file in flutter web

So im currently trying to send images from file picker to an api that had a file input, here is the postman display and the thing was, i've tried it with numerous way that was in other post, but none of them is working for me, this is the error that i get from my web browser console and this is the code that i've tried to work with:所以我目前正在尝试将文件选择器中的图像发送到具有文件输入的 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);

i don't think the main problem was the CORS, because the api log is indicating that the request is received, but no file was attached to that request.我认为主要问题不是 CORS,因为 api 日志表明已收到请求,但没有文件附加到该请求。

additional note: i've tried everything from the client side, and i cannot open/edit the backend, because it's a third party api (not owned by me).附加说明:我已经从客户端尝试了所有方法,但我无法打开/编辑后端,因为它是第三方 api(不归我所有)。

As I can see your errors main problem here first is data was rejected from your Server as the server not allowing you to upload files and throw Cross-Origin Access which you have to solve first and then you should try.正如我所见,您的错误主要问题首先是您的服务器拒绝了数据,因为服务器不允许您上传文件并抛出您必须首先解决的跨域访问,然后您应该尝试。

If your postman is able to upload images on server that is because postmen itself capable of solving Cross-Origin Acess Error, so here is the solution for the node.js如果你的 postman 可以上传图片到服务器,那是因为 postmen 本身可以解决 Cross-Origin Acess Error,所以这里是 node.js 的解决方案

If your backend is in node.js you can inject the below code into your middleware.如果您的后端在 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();
});

Or you can use localhost as a backend server.或者您可以使用 localhost 作为后端服务器。

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

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