Error occurred when sending form data while uploading a file

Upon trying to upload a file using the formData.append(key, value);, an error message is displayed in the value section:

The argument of type 'unknown' cannot be assigned to a parameter of type 'string | Blob'. Type '{}' is missing essential properties such as size, type, arrayBuffer, slice, and more.

Code snippet

const uploadSubtitle = async e => {
            e.preventDefault();
            const file = fileInput.current.files[0];
            const res = await Axios.get(`/api/movies/${currentMovie.movieId}/subtitles?user=${user.id}`);
            const { url, fields } = res.data;
            const newUrl = `https://${url.split('/')[3]}.s3.amazonaws.com`;
            const formData = new FormData();
            const formArray = Object.entries({ ...fields, file });
            formArray.forEach(([key, value]) => {
                formData.append(key, value);
            });
           //... further code
    };


<form onSubmit={uploadSubtitle}>
   <input type='file' name='subtitle' ref={fileInput} accept='.srt' />
   <button onClick={uploadSubtitle}>Upload</button>
</form>

Extra information

console.log(file) output displays

File 
{name: "Trainspotting-English.srt", lastModified: 1587840529000, 
lastModifiedDate: Sun Apr 26 2020 00:18:49 GMT+0530 (India Standard Time), 
webkitRelativePath: "", size: 103040, …}

lastModified: 1587840529000 lastModifiedDate: Sun Apr 26 2020 00:18:49 GMT+0530 (India Standard Time) 
{} name: "Trainspotting-English.srt" size: 103040 
type: "application/x-subrip" webkitRelativePath: "" __proto__: File

console.log(typeof file) reveals that it is object

Answer №1

The crux of the issue lies in the enigmatic nature of res, which first appears in this context:

const res = await Axios.get(`/api/movies/${currentMovie.movieId}/subtitles?user=${user.id}`);

res is classified as any, causing the type of fields to also become any. Consequently, formArray ends up being categorized as [string, unknown][], leading to the presence of value as unknown, thus triggering an error.

To address this issue at its root, we can incorporate a generic type within the Axios.get method like this:

const res = await Axios.get<{url :string, fields: {[key:string]:string}}>(`/api/movies/xxx/subtitles?user=xxx`);

As a result, res will now assume the type

{url :string, fields: {[key:string]:string}}
, consequently defining fields with the type {[key:string]:string}.

Regrettably, the spread operator does not deduce the correct types. The expression {...fields, file} resolves to {file: File}, which isn't particularly beneficial. Therefore, let's provide guidance for formArray:

const formArray : [string, string|File][] = Object.entries({...fields, file});

Now, value will possess the type string|File.

Complete example:

function App() {

    let fileInput = useRef<HTMLInputElement>(null);

    const uploadSubtitle = async (e: React.FormEvent) => {
        e.preventDefault();
        const file = fileInput.current!.files![0];
        const res = await Axios.get<{ url: string, fields: { [key: string]: string } }>(`/api/movies/xxx/subtitles?user=xxx`);
        const {url, fields} = res.data;
        const formData = new FormData();
        const formArray: [string, string | File][] = Object.entries({...fields, file});
        formArray.forEach(([key, value]) => {
            formData.append(key, value);
        });
    };
    return <form onSubmit={uploadSubtitle}>
        <input type='file' name='subtitle' ref={fileInput} accept='.srt'/>
        <button type="submit">Upload</button>
    </form>
}

This intensive effort can be streamlined by modifying the problematic line to read as follows:

formData.append(key, value as Blob);

Incorporating as Blob into the code won't alter the compiled JS but will effectively silence the TypeScript compiler's complaints.

Answer №2

My initial File data structure was causing an error: "Argument of type 'FileData' is not assignable to parameter of type String or Blob"

To resolve this issue, I made the following adjustments:

I updated the code to use form.append('file', value as {} as Blob); This change successfully stopped TypeScript from raising errors.

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

Record the success or failure of a Protractor test case to generate customized reports

Recently, I implemented Protractor testing for our Angular apps at the company and I've been searching for a straightforward method to record the pass/fail status of each scenario in the spec classes. Is there a simple solution for this? Despite my at ...

Exploring the possibilities of reading and writing data in localStorage?

Just starting out with Phonegap, jQuery Mobile, and HTML5 - so please bear with me as I navigate through this learning process! I'm having an issue and could use some help. When trying to use a variable from localStorage, the screen remains blank whe ...

Tips for navigating the HTML DOM without using window.scrollBy(x, y) (specifically for scrolling within an element)

Desiring to scroll down along with my selected document, I experimented with the following code. window.scrollTo(x, y); const body = document.getElementsByClassName("body")[0]; body.scrollTo(x, y); However, there are instances where it returns "undefined ...

Customize Your AJAX POST URL with Radio Buttons - A Step-by-Step Guide

I'm looking for some guidance on how to use AJAX to change the post URL based on a radio button selection. Do I need to use an if statement or is there another way? var barray = []; function cbutton() { $('input:radio[name="cheking"]:checke ...

Troubleshooting issues with a Node.js application on Azure App Service

Seeking assistance with deploying my first Node.js app on Azure App Service. Despite following Microsoft's guides and tutorials, my app is not functioning as expected. Although I can see my project in the Azure portal, when I attempt to access it via ...

When querying the model, the result may be undefined

I'm encountering an issue where I can't access the content of an array of documents in my model and it's returning undefined. Here is the model structure (Project.js): var mongoose = require('moongoose'); var Schema = mongo ...

Unable to execute ajax on dom ready in Internet Explorer 9

Here is some code that needs to be executed on DOM ready without any user interaction: if($.browser.msie){ console.log("Using getJSON"); $.getJSON(baseUrl,function(){ alert('hi'); }); }else{ setTimeou ...

Obtain a transformed mesh that has been displaced using a displacementMap within three.js

Seeking to extract and export the mesh affected by a displacementMap. The displacement of vertexes is determined by this line in the shader (taken from three.js/src/renderers/shaders/ShaderChunk/displacementmap_vertex.glsl): transformed += normalize(obje ...

Giving identification to a pair of elements located within the same column

Struggling with assigning IDs to two elements in a single column - a dropdown and a text element. Managed it in the first scenario, but encountering issues in the second one. Seeking assistance on this matter. Scenario 1: <td> <sele ...

The softAssert method is not available when trying to implement soft assertions within a TypeScript-based Protractor framework

Uncaught TypeError: assertion.softAssert is not a function I recently included a package called soft-assert using npm in my project. To install this package, I executed the following command: npm i soft-assert -g --save-dev Incorporated the following co ...

Apply a specific image layout once the drop event occurs

I have a container with 5 image pieces that need to be dropped into another container to complete the image. Once an image is dropped, I want to apply the style "position:absolute" so that it sticks to the previous image in that container. Although I have ...

The manager encountered an issue while querying for "Photo" data: EntityMetadataNotFoundError - no metadata could be found

I encountered an error while attempting to utilize typeorm on express: if (!metadata) throw new EntityMetadataNotFoundError(target) ^ EntityMetadataNotFoundError: Unable to locate metadata for "Photo". Below is my data source: import " ...

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

Guide on converting this function into a computed property within Vue

Is it possible to concatenate a fixed directory path, which is defined in the data property, with a file name that is determined using v-for? I encountered an issue when attempting to do this using a computed property. The error message displayed was: ...

The transfer of variables from AJAX to PHP is not working

My attempt to pass input from JavaScript to PHP using AJAX is not successful. I have included my JS and PHP code below: <!DOCTYPE html> <html> <head> <style> div{border:solid;} div{background-color:blue;} </style> </head&g ...

Unable to access a nested JSON object that has a repeated name

I'm relatively new to working with JSON, so the issue I'm facing may be simple, but I haven't been able to find a similar problem on stackoverflow. Here's my question: My goal is to access a nested JSON object like: pizza.topping.ratin ...

Iterate through the JSON response and send it back to Jquery

I'm almost done with my first jQuery autocomplete script and just need some assistance in understanding how to make the found elements clickable as links. Here is a snippet of my JavaScript code: $(document).ready(function() { var attr = $(&apos ...

What is the process for incorporating an external script into my Vue methods?

After a user registers, I need to send them a confirmation email using vue.js. I am looking to implement the script provided by . How can I incorporate the "Email.send" method into my vue.js application? <script src="https://smtpjs.com/v3/smtp.js"> ...

Steps for generating a time selection dropdown menu

My issue is with the functionality of my timepicker dropdown. Below is the code I am currently using: $(document).ready(function() { $('.timepicker-input').timepicker({ timeFormat: 'h:mm p', interval: 60, minTime: ' ...

How to retrieve the ID of a parent sibling using jQuery DataTables

I have encountered a peculiar issue while trying to retrieve the ID of a table's parent sibling. Prior to initializing jQuery DataTables, obtaining the table's ID poses no problem. However, once it is initialized and the table is built, retrievin ...