Troubleshooting vague errors with uploading large files in Golang's net/http protocol

I've encountered a challenging error while uploading large files to a server built with Golang's default net/http package. The upload process is defined as follows:

    uploadForm.onsubmit = () => {
        const formData = new FormData(uploadForm);
        const isPublic : boolean = (<HTMLInputElement>document.getElementById('public_switch')).checked;
        formData.append('file', (<HTMLInputElement>document.getElementById('file')).files[0]);
        formData.append('compression', (<HTMLInputElement>document.getElementById('compression')).value);
        formData.append('public', String(isPublic));
        const xhr = new XMLHttpRequest();
        xhr.open("POST", "/upload/");
        xhr.send(formData);
        xhr.onreadystatechange = function() {
            console.log(xhr.responseText);
        }
    }

The server, written in Golang, is initiated like so:

var server = &http.Server{
    Addr:         ":" + Configuration.Port,
    ReadTimeout:  300 * time.Second,
    WriteTimeout: 300 * time.Second,
    ReadHeaderTimeout: 300 * time.Second,
    MaxHeaderBytes: 500000000}

http.HandleFunc("/upload/", uploadFile)

server.ListenAndServe()

Upon receiving the file, it goes through the following processing code:

func uploadFile(w http.ResponseWriter, r *http.Request) {
    //Parsing the upload arguments into the values we shall be working with
    r.ParseMultipartForm(5000000000000000)

    file, _, err := r.FormFile("file")
    //etc

However, when reaching 'r.FormFile("file")' an error message stating "multipart: NextPart: EOF" is displayed.

Could there be specific settings for file limits or timeouts that I am missing in either the Go code or JavaScript? The file being uploaded is approximately 1.7GB and well within the supported HTTP limits.

Any suggestions on how I can improve debugging this issue without diving deep into FormFile or capturing the request itself? The code functions flawlessly with smaller files (only a few MB).

Answer №1

Let me share the solution to my own question for future reference.

The issue lies with the shortcomings of JavaScript on the web APIs for form and files handling.

Here is the JavaScript solution I devised:

const uploadFile = (form_id: string) => {
    const uploadForm: HTMLFormElement = <HTMLFormElement>document.getElementById(form_id);
    document.getElementById("submit_form").addEventListener("click", function(e) {
        e.preventDefault()

        let reader: FileReader = new FileReader();
        reader.readAsArrayBuffer((<HTMLInputElement>document.getElementById('file')).files[0]);

        reader.onload = function(evt) {

            const formData = new FormData(uploadForm);
            const isPublic: boolean = (<HTMLInputElement>document.getElementById('public_switch')).checked;
            formData.append('file', (<any>evt.target).result);
            formData.append('compression', (<HTMLInputElement>document.getElementById('compression')).value);
            formData.append('public', String(isPublic));
            const xhr = new XMLHttpRequest();
            xhr.open("POST", "/upload/");
            xhr.send(formData);
            xhr.onreadystatechange = function() {
                console.log(xhr.responseText + '  \n status is: ' + xhr.statusText);
            }

        };
    });

}

Although simple, it took a while to find due to cluttered online examples in the JavaScript community.

To handle large files, you should use a FileReader object as follows:

let reader = new FileReader();
reader.readAsArrayBuffer(dom_element_with_file_input.files[0]);

Then, you can utilize it like any other async web API:

reader.onload = function(e) {
    const your_file = e.target.result
}

'your_file' contains the file content for further use. In my case, I appended it to form data like this:

reader.onload = function(e) {
    const your_file = e.target.result
    const formData = new FormData(dom_element_of_type_form);
    formData.append('my_file', your_file);
    formData.append('other_stuff', 'a string with metadata');
}

I'm sharing this example since clear demonstrations of the FileReader API are scarce. I found some guidance at Mozilla documentation, but opted for 'readAsArrayBuffer' for speed enhancements.

Lastly, note that the reader API can be slow and resource-intensive, potentially leading to browser crashes with very large files. If you have insights or solutions to prevent such crashes, please share them with me.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Step-by-step guide to developing an Angular 2+ component and publishing it on npm

I need assistance with creating an AngularX (2+) component and getting it published on npm. My objective is to publish a modal component I developed in my current Angular App, though currently, I am focusing on creating a <hello-world> component. It ...

Passing props from parent component to map function in ReactJS results in undefined props

In my project, I dynamically create <textarea> elements using the map() function. Each textarea should have a unique value when the component is rendered. // Within the render method of ComponentA fruits.map((fruit) => { return <textarea na ...

Modify associated dropdown menus

I am trying to create an edit form that includes dependent select fields (such as country, state, city). The issue I am facing is that the edit only works when I reselect the first option (car brand) because I am using the event (change) with $event. How c ...

What is the process to designate a specific value to a key in an array?

I need assistance in updating the description array within the schema by adding the about and link values, followed by using the .save() function to store it in the database. Any guidance on this issue would be greatly appreciated. Thank you for your help. ...

Filter the object by its unique identifier and locate the entry with the highest score

I'm currently working on figuring out the proper syntax for sorting an object by ID and then identifying the highest score within that ID array. While I've managed to sort the object up to this point using conditionals and the sort() method, I&ap ...

Transform JSON time data from Coordinated Universal Time (UTC) to Indian Standard

Hello, I consider myself an amateur in the world of online javascript learning. Currently, I have come across a challenge that has left me stuck. I am working with a JSON time data provided in UTC format (e.g. 16:00:00Z) and my goal is to convert it to IS ...

Are reflection problems a concern when using type-graphql mutations?

Recently, I've been experimenting with integrating type-graphql into my nodejs project. While implementing @Query methods went smoothly, I'm facing challenges with the following code snippet in combination with Moleculer service. @Mutation() / ...

JavaScript checking the current page's URL is crucial for maintaining accurate and dynamic

I've attempted to verify the URL using this specific function. It functions properly with single text, but fails when a URL is inputted. jQuery(document).ready ( function () { //var regExp = /franky/g; //It works fine ...

Errors are being displayed in the console when attempting to use Vuex getters in a component. This is happening because the Vuex state properties are still null at the time the getters

When assigning results from GET requests to my Vuex state properties, it's expected that they won't be available instantly. However, I have a getter like the following: findChampion: (state) => (id) => { let championId = id.toString() ...

Is it possible to use v-if in conjunction with a style tag to specify a different source file? Alternatively, is there a more efficient method I

I attempted the example provided below, but unfortunately, it did not function as expected. The reason behind my endeavor is that adding numerous modifiers (--tuned) to achieve the desired outcome seemed impractical. Therefore, I decided to try and link ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...

What is the reason this JavaScript code functions properly within a <script> tag but not when placed in a separate .js

After researching various image sliders online, I came across this specific one. It worked perfectly fine when I included the JavaScript directly in a script tag within the HTML file. However, as soon as I tried to link it via a .js file, the slider stoppe ...

Maximizing the potential of Next JS 13 Server Components

Exploring the updates in Next JS 13, I have found it intriguing that every component is now a server component by default. This concept has been puzzling for me as I try to grasp how to effectively leverage this feature. For instance, my current challenge ...

Alternate the color over time using CSS

Is there a way to dynamically change the color of a div from black to white every two seconds, and then from white to black, continuously toggling as long as the div is visible? Essentially, I want the div to only be displayed when a user clicks and drag ...

Can a self-referential type truly exist?

There is a function that takes in a configuration object containing color definitions. For example: useColors({ colors: { RED: { hex: 0xff0000 }, GREEN: { hex: 0x00ff00 }, BLUE: { hex: 0x0000ff } }, doSomethingWithColor(getColor) { g ...

Is there a way to efficiently return an array of object and nested object keys with their full paths through recursion

My grasp of JS is still in its early stages, so understanding how the stack and recursion function can be challenging for me at this point. The task at hand involves displaying an array of object keys, including the parent object name if the object is nest ...

Issue with dynamic-rooms causing networked Aframe project to malfunction

I am currently working on a project using A-frame() along with the networked A-frame component: https://www.npmjs.com/package/networked-aframe To view the project, click here: I encountered an issue when attempting to replace the following code in scene. ...

The icon for the weather on openweathermap is currently not displaying

Take a look at what my webpage looks like: http://prntscr.com/dg6dmm and also check out my codepen link: http://codepen.io/johnthorlby/pen/dOmaEr I am trying to extract the weather icon from the api call and display that icon (e.g. "02n") on the page base ...

Implementing event dispatch on Push notifications received with Workbox

In my VueJS component, I have set up a listener for the pushMessageEvent event: <template> <div> <VueBotUI :options="options" :is-open="isOpen" :bot-typing="botTyping" :inpu ...

How can I deactivate the main color of the FormLabel when the focus is on the radio button group?

Is there a way to change the color of FormLabel to black instead of the primary color when the radio button group is focused? https://i.sstatic.net/h3hML.png const styles = { formLabel: { color: "#000" }, formLabelFocused: { color: "#000" ...