Search code examples
phpajaxapachehttp-status-code-413

PHP + Ajax: Uploading large content via Ajax (413 HTTP Code)


I've spent good 2 days on this issue and I'm reaching a desperation point. I am hitting my request limits when I am uploading file content via Ajax - Request Entity Too large. I am on an Apache server. I am able to modify php.ini and htaccess but not able to modify any configs beyond this as I do not have access to those.

Problem:

I have a base64 encoded content of an image that I need to upload to my server (roughly 1MB in size). I have tried uploading this value, which results in 413 error code. As an experiment, I've tried uploading an image using a <input type='file' /> field which works for images and files much bigger than 1MB. It seems I am hitting the 413 error only if I have data >1MB present in the request params (eg adding data in an input field, or adding base64 representation of an image into one of the request params). Uploading the same file using File input works fine though. The real issue is that in my website I can't have users upload image via File Input field. I only have the base64 content of the image that needs to be uploaded. Given that I can't modify my server settings, is there a way I can upload this content into my server??

Additional Info:

I am using JS FormData() object. The content of my form goes into this object and gets uploaded to my server. I can dynamically add values to this object using methods like formdata.append().

  • If I append large base64 string from above description, I hit a 413 error.
  • If I add a text field into the form and copy/paste the base64 string into the input field, I also hit the 413 error
  • If I upload the same image from my machine using <input type='file' /> field and upload the FormData object the image comes through fine.

Hope this is enough info. As a bonus - if anyone can explain why uploading the file via File Input works, but uploading the same data via a text field doesn't that would be quite beneficial also!


Solution

  • For anyone having similar problems in the future, I've found the answer in one of the answers to this question

    Essentially we'll add the base64 string as a blob to the formData object using:

    var formData = new FormData();
    var blob = new Blob(['Lorem ipsum'], { type: 'plain/text' });
    formData.append('file', blob,'readme.txt');
    

    This seems to mimic the behaviour of File Input.