How to send data in api without losing it - javascript

Below code i'm adding objects to media array in reactJS
const formData = new FormData()
formData.append('file', file, file.name)
const obj = {
'id': id,
'type': 'doc',
'data': formData,
url: file
};
setID(id + 1);
setMedia([...media, obj]);
Now i send it to api via axios
function addNew() {
setProgressing(true)
axios.post(uri + '/api/add', {
map_id: props.data.id,
questions: JSON.stringify(media)
})
.then(res => {
props.updateStep();
})
.catch(err => {
});
}
But on server end i receive object of array like below
see data and url is empty
{id: 1, type: "image", data: {{}}, url: {}}
this is request header
SetMedia code which call on each image upload
function handleUploadChange(e) {
handleClose();
const file = e.target.files[0];
if (!file) {
return;
}
const reader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = () => {
const formData = new FormData()
formData.append('file', file, file.name)
const obj = { 'id': id, 'type': 'image', 'data': formData, url: file };
setID(id+1);
setMedia([...media, obj]);
}
reader.onerror = function () {
console.log("error on load image");
};
}

i find solution for it.
i convert images in base64 and send string in request and on server side convert it again to images.

Related

How to send text and formData in one fetch call

I am trying to send text and formData in one fetch call to a Node.js backend using multer.
I can send formData on its own with no issues, but when I try and add text, the api call stays 'pending'.
Here is my fetch call that works just with formData:
const handleImage = async (e) => {
var formData = new FormData();
let file = e.target.files[0];
formData.append("image", file);
try {
const upload = await fetch(
`${process.env.NEXT_PUBLIC_SERVER_API}/uploadImage`,
{
method: "POST",
body: formData,
}
);
} catch (e) {
console.log("Something went wrong!");
}
};
Here is the same fetch call with text added that does not work:
const handleImage = async (e) => {
var formData = new FormData();
let file = e.target.files[0];
formData.append("image", file);
try {
const upload = await fetch(
`${process.env.NEXT_PUBLIC_SERVER_API}/uploadImage`,
{
method: "POST",
body: {formData, userId}
}
);
} catch (e) {
console.log("Something went wrong!");
}
};
It also doesn't work if I try and user JSON.stringify().
I do believe that you can't send a formData and json body at the same time (maybe there is a way somehow i don't know)
because multer will just take the file from formdata and the other property will be set to req.body so if you want to send userId you can try
const handleImage = async (e) => {
var formData = new FormData();
let file = e.target.files[0];
formData.append("image", file);
formData.append("userId", userId);
try {
const upload = await fetch(
`${process.env.NEXT_PUBLIC_SERVER_API}/uploadImage`,
{
method: "POST",
body: formData,
}
);
} catch (e) {
console.log("Something went wrong!");
}
};

How to recive uploded file in nodejs

i have a redux-from submission, console log look like this
{
id: "x",
parentId: "b",
editing: true,
logo: FileList,
}
Logo FileList contains my uploaded file name and file, i think
0: File(19355) {name: "11964821.jpeg", lastModified: ......
using fetch to send to nodejs, image contain my files and above data
function Update(image) {
const requestOptions = {
method: 'POST',
headers: { ...authHeader(), 'Content-Type': 'application/x-www-form-urlencoded' },
body: JSON.stringify(image)
};
return fetch(`${apiUrl}/API`, requestOptions).then(handleResponse)
.then( data => { return data; });
}
but this data not receiving nodejs, because is tried re.file etc.. its shows undefined
app.post('/image', upload.single('logo'), function (req, res, next) {
})
include formdata
const onSubmit = (image, dispatch)=>{
var formData = new FormData();
formData.append('logo',image.logo[0]);
var imageNew = {...image,formData};
dispatch(imageActions.companyProfileLogoUpdate(imageNew)) ;
}
now log is
formData: FormData {}
id: "5c66478b0814720a4365fe72"
logo: FileList {0: File(19355), length: 1}
parentId: "5c66478b0814720a4365fe71"
let formData = new FormData();
formData.append('logo' , {{your image file}}
// upload file as
let result = await sendServerRequestForForm(url,formData);
function sendServerRequestForForm(url,data) {
var promise = new Promise(function(resolve) {
resolve($.ajax({
url,
method : 'POST',
data,
processData: false,
contentType: false,
success: function(data) {
return data
},
error: function (err) {
try{
let responseStatus = err.responseJSON
// watch your response
}catch (e) {
console.log('Field to get response');
}
}
}));
});
return promise
}
for fetch API you can try this
let formData = new FormData();
formData.append('logo', fileList[0]);
fetch(url, {
method: 'post',
body: data,
})
.then(…);
move formData to fetch file and remove header content type, Try this
function Update(image) {
var formData = new FormData();
formData.append('logo',image.logo[0]);
const requestOptions = {
method: 'POST',
headers: { ...authHeader() },
body: formData
};
return fetch(`${apiUrl}/API`, requestOptions).then(handleResponse)
.then( data => { return data; });
}
First thing is for using fetch api for post content-type header should match typeof body. since your body is json stringified your contentType header should be 'application/json' . more about this .
Second. since you want to upload an image which a file you should use FormData without requirement of setting contentType: like below:
let formData = new FormData();
formData.append('logo', image.logo[0]);
const requestOptions = {
method: 'POST',
body: formData
};
fetch(`${apiUrl}/API`, requestOptions)
.then(handleResponse)...

"blob".then is not a function when trying to generate pdf in react js

I am sending the below response from my REST Api .
{
"value": "JVBERi0xLjQKJeLjz9MKMSAwIG9iago8PC9TL0phdmFTY3JpcHQvSlModGhpcy56b29tID0gMTAwOyk+PgplbmRvYmoKNSAwIG9iago8PC9Db2xvclNwYWNlL0RldmljZUdyYXkvU3VidHlwZS9JbWFnZS9IZWlnaHQgMTUwL0ZpbHRlci9GbGF0ZURlY29kZS9UeXBlL1hPYmphkNkwEVng0L00DhlcQ6ysIV4GNaOajLDQGlbKEIuFcJchdvr0W/z0aY+lZJyy+pmGsnrODq3AQiAQCAQCiRDHKaRFx0iOEAGhh40g1P0IsjS9pXbPlEzDoYf1OKTkDjFdQ6ysIXaYzMRC17KaLtIpQxdTKUPs9Gm646LMQnT6NJeFXjazUIotCx3mrcWQabf6qG8iEAgEAoEmsW7jOIXU6BidLK2BkEZBFP88qhr9R42IKBwiqdSMSBnlGjL2GlLDZOZqMuuUIZsuQ5bp0/xSMkdl9YZdyfy1GOK2W4z6JgKBQCAQaBJLFyDTZwphpxCJjpHQGGYbPAn/JQ/DX/YVtf/Rq19v18QeBP+Sh+Gv+wra/+jVr7foAKKKKACiiigD5g/aO/wCSh6f/ANgqP/0bLXj9ewftHf8AJQ9P/wCwVH/6Nlrx+gAooooAK6DwJ/yUPw1/2FbX/wBGrXP10HgT/kofhr/sK2v/AKNWgD7fooooA8f/AGjv+Seaf/2FY/8A0VLXzBX0/wDtHf8AJPNP/wCwrH/6Klr5goAK+n/2cf8Aknmof9hWT/0VFXzBX0/+zj/yTzUP+wrJ/wCioqAPYKKKKACiiigAooooAKKKKACiiigD5g/aO/5KHp//AGCo/wD0bLXj9ewftHf8lD0//sFR/wDo2WvH6ACvt/wJ/wAk88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KJSVFT0YK",
"transid": "transid"
}
I am trying to convert the value which is byte data to pdf using React js.
Below is my implementation:
handleSubmit = e => {
e.preventDefault();
let url = "http://localhost:8080/getPDF"
fetch(url, {
method: "POST",
body: JSON.stringify(this.state.transId),
})
responseType: 'blob'
.then(response => {
//Create a Blob from the PDF Stream
const file = new Blob(
[response.value],
{type: 'application/pdf'});
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
})
.catch(error => {
console.log(error);
});
};
But I am getting the following error.Can anyone please suggest where I am going wrong?
Uncaught TypeError: "blob".then is not a function
You cannot do .then() after a string (must follow a promise). You probably meant this line responseType: 'blob' to be one line higher up, inside the object?
handleSubmit = e => {
e.preventDefault();
let url = "http://localhost:8080/getPDF"
fetch(url, {
method: "POST",
body: JSON.stringify(this.state.transId),
responseType: 'blob' // <-- MOVE THIS LINE INTO REQUEST
})
.then(response => {
//Create a Blob from the PDF Stream
const file = new Blob(
[response.value],
{type: 'application/pdf'});
//Build a URL from the file
const fileURL = URL.createObjectURL(file);
//Open the URL on new Window
window.open(fileURL);
})
.catch(error => {
console.log(error);
});
};

Is it possible to send data and files in the same request?

I have an API that receives uploads of APP files and images
To send from APP to the API I use fetch
const data = new FormData();
let i = 0;
export const dataPush = (fileUri, fileType, fileName) => {
data.append('file'+i, {
uri: fileUri,
type: fileType,
name: fileName
});
i++;
};
export const uploadFiles = () => {
console.log(data);
fetch('http://192.168.0.23/apiapp/public/api/annex', {
method: 'post',
body: data
}).then(res => {
console.log(res)
});
}
But I'd like to send in the same request data obtained from a form
But I did not find a way to do it, always or just send the data, or just send the files
Is it possible to send everything in the same request? And if possible, how?
You just append whatever data that you desire that isn't file data to the FormData object.
data.append("not_a_file", "This is a string");
I did so based on Quentin's response and it worked
const formData = new FormData();
const i = 0;
export const filePush = (fileUri, fileType, fileName) => {
formData.append('file'+i, {
uri: fileUri,
type: fileType,
name: fileName
});
i++;
};
export const dataPush = (name, content) => {
formData.append(name, content);
};
export const uploadFiles = () => {
fetch('http://192.168.0.23/apiapp/public/api/annex', {
method: 'post',
body: formData
}).then(res => {
console.log(res._bodyText)
}).catch(error => {
console.log(error.message)
});
}

Javascript/React fetch api sending image via formdata

I'm trying to send a file object (image) as a multipart/form-data request using the javascript fetch api.
The code below shows how I convert the file object to string format.
The image parameter is an array of File objects. I want to send the first image of that array to a webservice.
onImageUpload = ((image) => {
//File to arraybuffer
let fr = new FileReader();
fr.onload = function(e) {
var text = e.target.result;
AccountService.uploadProfileImage(localStorage.getItem('session-key'), text)
.then((ro) => {
if(ro.code == 200) {
this.showSnackbar("Profile image uploaded successfully!");
}
else {
this.showSnackbar("Error uploading your image. Please try again later.");
}
})
}
fr.readAsText(image[0]);
})
Below is my uploadProfileImage function, which makes the post request using the fetch api.
static async uploadProfileImage(sessionKey, image) {
var reader = new FileReader();
let ro = new ResponseObject();
let fd = new FormData();
let imgObj = new Image();
imgObj.src = image;
let blob = new Blob([new Uint8Array(image)], { type: "image/jpg"});
fd.append("name", localStorage.getItem('username'));
fd.append("file", blob);
return new Promise((resolve, reject) => {
fetch(UrlConstants.BASE_URL + this.urlUploadProfileImage, {
method: "POST",
headers: {
'Authorization': 'Bearer ' + sessionKey,
"Content-type": "multipart/form-data;"
},
body: fd
}).then((response) => {
ro.code = response.status;
return response.text();
})
.then((text) => {
ro.message = text;
resolve(ro);
})
.catch((ex) => {
reject(ex);
})
});
}
When I sent the image parameter in the uploadProfileImage without converting it into a blob the data are being sent, but i need the blob to have the Content-Type: "image/jpg" in the request as the api I'm working with can't handle the request without it.
The problem that the image is not being included in the request.
How can I do that?
Thanks for your help.

Categories

Resources