'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:

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.

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).



Solution 1:[1]

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

If your backend is in node js you can inject the below code into your middleware.

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Parth Virani