Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  47] [ 5]  / answers: 1 / hits: 6974  / 3 Years ago, fri, december 10, 2021, 12:00:00

I would need to find a solution to send via a single axios POST request both of the following:



  1. json structure

  2. binary file (excel file)


How can I achieve this?


  let files = event.target.files;
const fileReader = new FileReader();
fileReader.readAsText(files[0], null);
fileReader.onload = () => {
this.fileContent = fileReader.result;

let binaryDataForObject = this.fileContent;

let referenceDataStructure = {
textData: textDataForObject,
binaryData: binaryDataForObject,
referenceDataFileExtension: this.referenceDataFileExtension,
userProvidedDataTypes: this.columnTypes
};
}

this.axios
.post(
"http://url,
referenceDataStructure
)

This works technically but on the java side I couldn't figure out, how to decode the binary data (encoded as a string) so that it is treated as an excel file.


Thank You in advance for any meaningful responses.
Lubos.


More From » java

 Answers
2

  1. With simple POST request you can send only up to 1mb of binary data

  2. To send binary and text in one request you should use FormData


Check out this answer for information


Update 14.12


How I managed to do this in my recent project was using FormData


So firstly you need to get file as a blob:


const fileReader = new FileReader()
// Here we will get the file as binary data
fileReader.onload = () => {
const MB = 1000000;
const Blob = new Blob([fileReader.result], {
// This will set the mimetype of the file
type: fileInputRef.current.files[0].type
});
const BlobName = fileInputRef.current.files[0].name;
if (Blob.size > MB) return new Error('File size is to big');

// Initializing form data and passing the file as a param
const formData = new FormData();
// file - field name, this will help you to read file on backend
// Blob - main data to send
// BlobName - name of the file, default it will be name of your input
formData.append('file', Blob, BlobName);

// Append json data
formData.apped('some-key', someValue)

// then just send it as a body with post request
fetch('/api/submit-some-form-with-file', {
method: 'POST',
body: formData
})
// Handle the rest
.then()
}

fileReader.readAsArrayBuffer(fileInputRef.current.files[0])

You can wrap this example in handle submit function in react and like or use it as is


[#597] Wednesday, December 1, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jensenb

Total Points: 634
Total Questions: 102
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Thu, Jun 24, 2021
3 Years ago
jensenb questions
Thu, Jun 24, 21, 00:00, 3 Years ago
Wed, Apr 7, 21, 00:00, 3 Years ago
Tue, Jun 4, 19, 00:00, 5 Years ago
Mon, Mar 25, 19, 00:00, 5 Years ago
Thu, Feb 21, 19, 00:00, 5 Years ago
;