I encountered a 500 error while trying to post an array of images using axios

I encountered an issue with my code that involves allowing users to upload multiple images. Whenever a user uploads pictures and a request is sent to the server, I keep getting a 500 error code.

Here's the snippet of the problematic code:

ChangeImages(images) {
      this.images = images;
      console.log("imagesEmit", this.images);
      console.log(this.step);
      console.log("images", images);
      console.log("thishome", this.home);
      const formData = new FormData();
      let id = this.homeId;

      formData.append(
        "data",
        JSON.stringify({ file: this.images[0], position: 1 })
      );
      console.log(formData);
      axios
        .post(`/api/upload-home-picture/${id}`, formData, {
          headers: { "Content-Type": "multipart/form-data" },
        })
        .then((response) => {
          this.home.images[0].push(response.data);
        });
    }

The issue arises when sending the request within a listener. Here are the results from the console logs:

this.images:

"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAABsoA…wD3k6myVTczaWMZ5Ebv8P2lNvc037YOAAAAAASUVORK5CYII="

this.home:

funding_round_end: (...)
funding_round_start: (...)
funding_round_time: (...)
hpi_zip_avg_appreciation: (...)
id: (...)
images: (...)
info: (...)
interest: (...)
invest_now: (...) 

Additionally, here's the payload:

{"images":"data:image/png;base64,

And the backend code snippet:

@bp.route('/upload-home-picture', methods=['POST'])
@login_required
def upload_home_picture():
    # TODO test permission
    data = json.loads(request.form['data'])
    home_id = data['home']
    home = UserHome.query.get(home_id)
    url = _upload_file()
    db.session.add(UserHomeImage(url=url, home=home, pos=0))
    db.session.commit()
    result = dict(url=url, pos=0)
    return jsonify(result)

Answer №1

Sending an image without using JSON.stringify is the preferred method.

onUpload() {      
    let formData = new FormData();
    formData.append('file', this.images[0]);
    axios.post(
        `/api/upload-home-picture/${id}`
        ,formData
        ,{headers: {"Content-Type": "multipart/form-data"}}
    )
    .then((response) => {
          this.home.images[0].push(response.data);
    });
    .catch(e => {
       //...
    })
}

This approach will make it easier to access the image as a file in Python.

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

Retrieve the source of the image within the button that you've just clicked

I'm currently working on retrieving the SRC attribute of an image contained within a button that triggers the opening of an accordion built with Bootstrap. However, I am struggling to find a suitable example of what I specifically need. So far, most e ...

How come my 'then' promise chaining continues to execute even after I have already sent the response?

Implementing a sign up process using code in the controller of a Node.js application. Here is the full code snippet: const bcrypt = require("bcrypt") const User = require("../models/user") // mongoose model const ResponseData = require("../models/structu ...

Looking for assistance with submitting two forms in one AJAX request to a single file.php

Hey there, I'm looking to submit 2 forms using a single ajax or jquery request to a common file. The code snippet I currently have is as follows: <form id="filter-group1" class="form" target="remember" autocomplete="on" method="post"> <i ...

creating dynamic parameterized URLs in Laravel

For example: Here are a few names. - Mujib - Amjed - Anees When someone clicks on "Mujib," the URL should remain the same and only the parameter should change. When someone clicks on "Amjed," the URL parameter should change to . ...

NativeScript has just faced a critical issue: an Uncaught ReferenceError has occurred stating that the variable __UI_USE_EXTERNAL_RENDERER__ is not

While working on iOS on my Mac, I encountered an unexpected error. ***** Fatal JavaScript exception - application has been terminated. ***** NativeScript encountered a fatal error: Uncaught ReferenceError: __UI_USE_EXTERNAL_RENDERER__ is not defined at (f ...

Exploring the code within the $(function () { ... }) block

I am working with a .NET web control that contains some JavaScript code structured as follows: <script type="text/javascript"> function doSomethingImportant() { // Code for an important task... } $(function () { // Som ...

Align a div both horizontally and vertically using only JavaScript

Is there a way to center a div both horizontally and vertically without knowing its height/width using pure JavaScript instead of jQuery? I have been able to achieve it with jQuery but want to avoid dependencies. Any ideas on how this can be accomplished ...

What is the best way to transfer the http server variable between different layers in node.js without requiring it in a separate file?

I've developed a nodeJS application that involves creating a server in the file server.js. The code looks like this: http.createServer(app).listen(app.get('port'), function (err) { if (err) { console.error(err); } else { ...

Issue with implementing a custom filter for currency in AngularJS code

I'm tackling a pretty straightforward task here. I just need to integrate a currency filter into the custom filter that I coded. Take a look at the code snippet below: var app = angular.module('testapp', []); app.controller('MainCt ...

Using the index of a v-for loop as the value for v-model

I am facing a challenge in setting the index of a v-for loop to a dynamic v-model. I have tried a method that works, but it is not elegant and results in errors in the console: Here is my template section: <div v-for="(ob, index) in $v.especifications ...

Perform an AJAX call from the main file after inserting data using AJAX beforehand

I am in need of assistance with a question I have. On a page, an AJAX function is executed after the page finishes loading, creating a table in PHP that contains two buttons: one for changing passwords and the other for deleting. This table is then injecte ...

It is not possible to attach separate links to images in a JavaScript slider

I am struggling with linking individual images in a JavaScript slider for a client's website. The slider is fully functional and works well, but I can't seem to figure out how to link the images properly. When I remove items from <--ul class= ...

When logging out, Redux fails to revert back to my original state

Following the dispatch of my redux action logout, I aim to reset to the initial state. However, when using nextjs, the logout reducer in authenticateSlice.js doesn't seem to execute as expected. Additionally, I had implemented redux-persist for mainta ...

Jest / eslint error: Function has no defined return type

I'm currently working with Jest in my codebase const fetchData = async () => { await API.fetchDataAsync(param); }; await expect(fetchData()).rejects.toThrowError(CustomError); However, I encountered an eslint error 92:28 error ...

Express.js is unable to redirect to a customized URL scheme

I'm currently having an issue with redirecting users to a custom URL scheme using Express.js in order to launch an app on my iPad (using "example://"). Below is the code I have written to handle the redirection from a button press on a page hosted on ...

Having trouble reaching an element within a successful Ajax call

I have encountered an issue where the element is not being recognized when putting an ajax call inside another ajax call. Here is an example of the code: $.ajax({ url: 'controleFatAcoes.php', type: 'post', dataType: 'h ...

Issues with the directory for Chrome

Currently, I am utilizing jQuery and running an HTML file on my local machine without a server. Interestingly, the code works perfectly fine on Firefox but encounters issues on Chrome: $('#result').load('test.html'); It appears that t ...

Is there a way to eliminate the legend symbol for just one legend in Highcharts?

Looking to customize a legend in Highcharts but facing limitations due to Plot Lines and Bands not having legends. To work around this, I have added an empty series that acts as a toggle for showing/hiding plot lines. Since my plot lines are vertical, I im ...

When requesting a JSON file, the Express route does not get executed

I have set up a route in my Express application to execute a specific line of code and then return a JSON file. However, I am facing an issue where the file is returned but the intended code execution is not happening. Here is the snippet of my server-sid ...

Assigning multiple values to a key within a JavaScript object

I have a task that needs to be completed as outlined below: $rootscope.$on('function', var1, var2, var3){ var renderObejcts = $('.launch').fullGrid({ events: function(zone1, zone2, callback) { //performing ...