Combining JSON parameter and multipart/form-data file in a single request using Vue.js

Is there a way to send both JSON parameters and multipart/form-data files in a single request using Vue, similar to how Postman does it? https://i.sstatic.net/CMi3D.png

I've been looking into how to submit "multipart/form-data" from VueJs. What I need is to include an image file in multipart format along with other parameters in a single JSON object (with content-type as json). Is it possible to combine these parameters in one HTTP request?

The main challenge is figuring out how to handle sending both JSON parameters and multipart files in a single POST request.

Answer №1

Before anything else, it's important to note that this question is not specifically related to Vue. A potential solution can be found in this response. Alternatively, if the content type of the request is not a critical factor, one could utilize simple FormData to easily include an image and send the JSON as plain text. However, implementing this approach may require additional parsing or mapping on the server side to align with your model.

Answer №2

In a similar situation, I encountered the same issue and wanted to share my solution. My goal was to upload an image, kind, name, and eventID.

let logoForm = new FormData
logoForm.append('image', this.logo1)
logoForm.append('kind', 'logo1')
logoForm.append('name', this.$refs.logo1.files[0].name )
logoForm.append('eventID',eventID)


axios.post(`/upload`, logoForm,
            
   {
      headers:{
          'Authorization' : `${token}`,
          'Content-Type': `multipart/form-data; boundary=${logoForm._boundary}` 
  },    

  }).then((res) => {

     console.log(res)


  }).catch((error) => {

    console.log(error)

  })

Please note that the correct parameter format for postdata should be (url , FormData) and not (url, {data: FormData})

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

Deciphering JavaScript script within a Node.js module

// =============================================================================== // Auth // =============================================================================== const admin = require('firebase-admin'); //what happens if i move th ...

Is it necessary to have both variables present in an if statement for it to be evaluated?

In an attempt to determine if a custom Date widget in JavaScript is empty or not, the following function is created. The challenge lies in the fact that there are multiple variations of this widget - some display M/D/Y fields, while others may only show M/ ...

How can I retrieve the identifier in Socket.io?

Is there a way to retrieve the unique Id from the server using socket.io? I attempted using clients[socket.id] = socket; However, I encountered an error stating: connections property is deprecated. use getconnections() method Does anyone have any sugg ...

Generate a link that can easily be shared after the content has loaded using

One feature on my website involves a content container that displays different information based on which list item is clicked (such as news, videos, blogs, etc.). This functionality is achieved by using jQuery's load method to bring in html snippets ...

Threejs: Illuminating the spotlight with visibility

For my current project, I am attempting to create a visible spotlight similar to the one used by Batman. I want that cone of light that pierces through the night sky. Unfortunately, I do not have any experience with graphics or 3D design, so I am strugglin ...

BufferGeometry: techniques for rendering face groupings

I have 2 different shapes and 2 sets of patterns. My primary objective is to sometimes hide a portion of the first shape (requiring 2 groups) while simultaneously displaying a section of the second shape (only needing 1 group). Prior to the r72 update, I u ...

Accessing Vue components with distinct identifiers

I need help figuring out how to remove a user from the team by passing both the team ID and the user ID in the same URL. I attempted to pass two parameters, but I am encountering difficulties with deleting users from the team in my VUE file. actions: de ...

using variables as identifiers in nested JSON objects

Within my code, there is a JSON object named arrayToSubmit. Below is the provided snippet: location = "Johannesburg, South Africa"; type = "bench"; qty = 1; assetNumber = 15; arrayToSubmit = { location : { type : { 'qty' ...

The React-Big-Calendar Drag and Drop feature in the month view consistently drags events from the leftmost column

I'm seeking assistance with a bug I've encountered while using the big-react-calendar. The issue arises when dragging an event, as it consistently moves to the leftmost column regardless of mouse position. However, shifting the event to a differe ...

Navigating through pages using Nuxt UI-pagination

Having some trouble with setting up the pagination feature from Nuxt UI. Despite trying to research through documentation and videos, I can't seem to figure out how to connect my data to the component. <template> <div> ...

What is the reason behind Chrome's automatic scrolling to ensure the clicked element is fully contained?

Recently, I have observed that when performing ajax page updates (specifically appends to a block, like in "Show more comments" scenarios) Chrome seems to automatically scroll in order to keep the clicked element in view. What is causing this behavior? Wh ...

efforts to activate a "click" with the enter key are unsuccessful

I'm attempting to enhance user experience on my site by triggering the onclick event of a button when the enter key is pressed. I've tried various methods below, but all seem to have the same issue. Here is my HTML (using Pug): input#userIntere ...

Having trouble getting your Bootstrap v4 carousel to function properly?

Currently, I have implemented the carousel feature from Bootstrap v4 in a Vue web application. I am following the same structure as shown in the sample example provided by Bootstrap, but unfortunately, it is not functioning correctly on my local setup and ...

Investigating nearby table cells

I am in the process of creating a game called Dots and Boxes. The grid is filled with numerous dots: <table> <tr> <td class="vLine" onclick="addLine(this)"></td> <td class="box" ...

Tips for relocating a popup window''s position

A situation has arisen in my application where a popup window is opened with the following code: function newPopup(url, windowName) { window.open(url,windowName,'height=768,width=1366,left=10,top=10,titlebar=no,toolbar=no,menubar=no,location=no,d ...

An efficient method for removing a column using JavaScript

Hello, I'm seeking assistance with the following code snippet: $(document).on('click', 'button[id=delete_column]', function () { if (col_number > 1) { $('#column' + col_number).remove(); $('#col ...

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Checkbox Event Restricts Access to a Single Class Variable

As a beginner in AngularJS (just diving in this week), I've encountered an issue with a checkbox input connected to an ng-change event. <input type="checkbox" ng-model="vm.hasCondoKey" ng-change="vm.onKeyCheckboxChange()" /> The ng-change even ...

Tips for defining a function without an arrow as a parameter

Understand that there may be individuals quick to flag this as a duplicate question, but trust me when I say that I have exhaustively searched on Google for almost an hour before turning to ask here. methods: { stylizeHeader: debounce(event => { ...

The authService is facing dependency resolution issues with the jwtService, causing a roadblock in the application's functionality

I'm puzzled by the error message I received: [Nest] 1276 - 25/04/2024 19:39:31 ERROR [ExceptionHandler] Nest can't resolve dependencies of the AuthService (?, JwtService). Please make sure that the argument UsersService at index [0] is availab ...