2
votes

I am using react with fetch for sending an image to the server.
I have tried using Content-type = application/x-www-form-urlencoded to pass my data to the server but it replaces special characters with spaces (i.e. + becomes a space).
I have switched the header to be Content-type: multipart/form-data but that throws the error

Failed to load resource: the server responded with a status of 500 (Internal Server Error).

I have added a boundary to the Content-type as boundary=abcdefg.
That did not change anything and I am not sure what my boundary would be.
Finding a clear answer with straight forward examples about boundaries have been impossible to get.
The data that I am sending is a large string.
If needed I can post that as well.

Here is a sample of the code that is causing the problem:

SaveTest4(data: string) {
    const options = {
        method: 'post',
        headers: {
            "Content-type": "multipart/form-data; boundary=abcdefg"
        },
        body: 'data=' + data
    }
    fetch('api/DataPoint/AddTest4', options);
}
1
have you tried something like: body: 'data=' + encodeURIComponent(data) - SamHecquet

1 Answers

0
votes

Based on part of your analysis, it sounds like you're trying to send base64-encoded data. A content type of application/x-www-form-urlencoded will result in the server performing URL decoding, which will replace each instance of + in the content body with a space character.

When you used a content type of multipart/form-data, the server fails with status 500 because the data you provided wasn't a properly constructed MIME document.

My psychic debugging powers tell me that you're trying to post a base64-encoded file to a ASP.NET MVC WebAPI endpoint that's expecting a JSON document. You might have a controller method that looks like this:

[HttpPost("api/DataPoint/AddTest4")]
public void AddTest4([FromBody] string data) { ... }

If you send with a content type of application/json, this endpoint will expect a document that looks like this:

"{base64-encoded-data}"

Note that there are quotes around the data, because a quoted string is a proper JSON document. You'd just use JSON.stringify() to create the quoted string in this case, which would escape any quotes within the string correctly.

If you send with application/x-www-form-urlencoded, you'd need to send a document that looks like this:

data={base64-encoded-data}

But, as you note, you'd have to make sure you escape all of the special characters in the payload; you can do this using window.encodeURIComponent(), which would translate each "+" to "%2B", among other things.

If the files that you're uploading to this endpoint are large, it would be significantly better to use an instance of FormData. This would allow the browser to stream the file to the server in chunks instead of reading it into memory and base64-encoding it in JavaScript.