send file to server axios - reactjs

I am trying send file to server with laravel api and react but the response is null this my code in frontend
let File;
const onChangeHandler = (e) => {
File = (e.target.files[0]);
}
const send = () => {
const formData = new FormData();
formData.append("media", File);
console.log(formData)
try {
PostRequest.post("/upload-post", {"media": formData}).then(r => console.log(r.data)).catch((e) => console.log(e));
} catch (error) {
console.log(error)
}
}
and my header :
headers: {
"Content-Type": "multipart/form-data",
"Accept":"application/json",
"Authorization": Token
}
and network tab
img
File log
File log

Related

How to make file upload in React

i have api like :
static async addTenderAttachment(documentId: number, file: File) {
const request = baseApi.getClient();
const formData = new FormData();
formData.append('attachments', file, file.name);
const options: AxiosRequestConfig = {
url: `/clients/Documents/Requests/${documentId}/Attachments`,
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
data: formData,
};
try {
const response: any = await request(options);
console.log(response);
return { response };
} catch (error) {
return { error };
}
}
also have upload component :
<div className={styles.col}>
<FileInput
label='DocumentFile'
placeholder={
attachments[0]
? attachments[0].name
: ' No file'
}
onChange={onAttachFile}
/>
and have onChange for that component :
const onAttachFile = useCallback((file: File) => {
if (file !== null) {
AttachmentApi.addTenderAttachment(
formValues.id,
file,
).then((resp) => {
console.log('successfully added file ', resp);
getAttachments();
});
}
}, []);
So as you see, i can add file only to existing tender, because only existing ones have documentId,
on createTender window there is no id, only after creating it appears.
Question is, how to make file upload work without id number..?

Send Multiple Data With Axios

I have a problem , my problem is when i send multiple data with axios , the image in formdata dosen't send , but when i send only the formdata it works , if any know how to send multiple data ins axios just give me what's the solution
const onSubmit = async (data) => {
if(loading) return ;
setLoading(true);
const formData = new FormData();
formData.append("image",image);
let details = {
name:data.name,
image:formData,
price:data.price,
description:convertToRaw(editorState.getCurrentContent()).blocks[0].text,
qty:data.qty,
promo:data.oldPrice,
categorie:data.categorie,
// images:[image,image2,image3,image4]
}
try{
let config = {
headers:{
authorization:"Authorization Token "+jwt,
"Accept": "application/json",
"Content-Type": "multipart/form-data",
}
}
await axios.post('../../api/products',details,config)
.then(res => console.log(res.data))
.then(setLoading(false))
.catch(err => console.log(err))
}catch(err){
console.log(err);
}
}
I would do something like this while uploading with images:
const onSubmit = async (data) => {
if(loading) return ;
setLoading(true);
const formData = new FormData();
formData.append("image",image);
let details = {
name:data.name,
price:data.price,
description:convertToRaw(editorState.getCurrentContent()).blocks[0].text,
qty:data.qty,
promo:data.oldPrice,
categorie:data.categorie
}
for (let key in details) {
formData.append(key, details[key]);
}
try{
let config = {
headers:{
authorization:"Authorization Token "+jwt,
"Content-Type": "multipart/form-data",
}
}
await axios.post('../../api/products',formData ,config)
.then(res => console.log(res.data))
.then(setLoading(false))
.catch(err => console.log(err))
}catch(err){
console.log(err);
}
}

extract csv file from url in react

i have a url which onclick downloads me a csv file.I want to fetch data from that url and show it in console.How can i do it?
const downloadCsv = async () => {
try {
const target = `https://connect.emgsrv.com/wT3Kjzu4B3P43VQikYjq/wT3Kjzu4B3P43VQikYjq.CSV`; //file
const res = await fetch(target, {
method: 'get',
mode: 'no-cors',
headers: {
'content-type': 'text/csv;charset=UTF-8',
//'Authorization': //in case you need authorisation
}
});
const data = await res.text();
console.log(data,'hahah');
} catch (err) {
console.log(err)
}
}

How to send a file from ReactJs to Flask using Axios

I am attempting to send a file from a ReactJs Frontend, using an axios call, to a flask Backend.
Here is my axios call:
const audio_file = new File(buffer, 'recording.mp3', {
type: blob.type,
lastModified: Date.now()
});
const blobURL = URL.createObjectURL(blob);
this.setState({blobURL, isRecording: false, recorded:true})
let options = {
method: 'POST',
url: flaskEndpoint + "audio/1",
file: audio_file,
crossOrigin:'*'
}
console.log(options)
axios(options)
.then(response => {
console.log(response)
})
.catch(error => {
console.log("Error in the axios call:" + error);
})
At the moment my flask method looks like this :
#app.route('/audio/<int:user_id>', methods=['POST'])
#cross_origin()
def make_audio(user_id):
print(request.files.get('recording.mp3'))
print(request.files)
return 0
Here is the console of the python app:
And here is the web console of the React App:
Am I making a mistake here?
Edit
Ok I tried the suggestion of converting the file to base64 and then sending the file the backend.
This is my new axios call.
let options = {
method: 'POST',
url: flaskEndpoint + "audio/1",
data: convertBlobToBase64(blob),
// file: audio_file,
crossOrigin:'*',
headers: {
'Content-Type': 'application/json'
},
json: true
}
console.log(options)
axios(options)
.then(response => {
console.log(response)
})
.catch(error => {
console.log("Error in the axios call:" + error);
})
});
Here is the convetBlobtoBase64 functions (borrowed from: https://gist.github.com/n1ru4l/dc99062577b746e0783410b1298ab897)
const convertBlobToBase64 = blob => new Promise((resolve, reject) => {
const reader = new FileReader;
reader.onerror = reject;
reader.onload = () => {
resolve(reader.result);
};
reader.readAsDataURL(blob);
});
And here is what is being sent to the backend:
I think this answers my question, although I will create another to work out how to access the data on the flask end.

Sending Multipart file and #RequestBody in single request

In the React web app I'm developing,there is a file upload part with some user data.However, when I'm trying to upload files, server throws the following error.
org.apache.tomcat.util.http.fileupload.FileUploadException: the
request was rejected because no multipart boundary was found
React side
function fileChangedHandler(event) {
let formData = new FormData();
formData.append("file", event.target.files[0]);
formData.append("name", event.target.files[0].name);
SENDER.post(
"/api/task_resources",{
addedBy: parseInt(localStorage.getItem('id')),
taskId: parseInt(props.taskId)
},{
params: {
file: formData
}
}
)
.then(res => {
if (res.status === 200) {
alert("upload suc");
window.location.reload()
}
})
.catch(err => alert("err"));
}
My Spring Boot controller is as follows.
#PostMapping("/task_resources")
public void addResourceToTask(#RequestParam("file") MultipartFile file,#RequestBody AddTaskResourceRequest addResReq) {
String fileName = fileService.storeFile(file);
String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/api/downloadFile/")
.path(fileName)
.toUriString();
UploadFileResponse response = new UploadFileResponse(fileName, fileDownloadUri,
file.getContentType(), file.getSize());
taskResourceService.addResource(addResReq, fileDownloadUri);
}
You need to send the request using multipart/form-data if your server is especting that. Here is my example implemented using Axios.
const postGalleryImageRequest = async (sessionToken, userLogged, image) => {
const data = new FormData();
data.append('newImage', image);
const result = await api.post('business/' + userLogged.businessId + '/gallery', data, {
headers: {
Authorization: sessionToken,
'Content-Type': 'multipart/form-data',
}
}) .then((response) => {
return response.data
})
.catch(error => {
....
})
return result;
}

Resources