extract csv file from url in react - reactjs

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)
}
}

Related

Format error when downloading Blob from React

I'm trying to download a Blob from React that can be either a PDF or an image(jpg, jpeg, png...). PDF's are downloading good from the next code but images not. I get this files from Laravel Backend with an return response()->download($full_path);
The request in React is the next one:
export const getFileApi = async (token, documentType) => {
const url = API_URL + `commerces/getFileDoc`;
try {
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: "Bearer " + token,
},
body: JSON.stringify({document_type: documentType})
});
const data = await response.blob();
console.log(data);
const link = document.createElement("a");
link.href = URL.createObjectURL(data);
link.download = documentType;
link.click();
if(data.errors) {
return {
error: data.errors
}
} else {
return {
data: data,
error: null
}
}
} catch (error) {
console.log(error);
return {
error: JSON.stringify(error)
}
}
Console.log of data is printing this:
When I open the image with Windows 10 the error says: "Seems that format of this file is not compatible"
Thank you beforehand.

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 file to server axios

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

How to send body with formData inside as a key fetch api

When I try to send image and a path to Api, it sends like [object Object]
export async function uploadImageToCDN(image: FormData, directory: string = 'dir'): Promise<any> {
const token = await authoriseInApi()
const headers = []
headers.push(['Authorization', `Bearer ${token}`])
const data: Content = new Content('multipart-file', {
file: image,
dir: directory
})
return post<any>('https://test-api.test.com/files/upload', data, headers)
}
This is how I collect data and send to Api:
const formData = new FormData()
const imageBase64 = await getBase64(file)
const imageUri = dataURIToBlob(imageBase64)
formData.append('image', imageUri)
const res = uploadImageToCDN(formData)
What is a mistake?
You need to use JSON.stringify(data) to send object parameter:
return post<any>('https://test-api.test.com/files/upload', JSON.stringify(data), headers)
Or if you want to use fectch try same thing:
//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
I wrote xhr request and everything work fine.
Here is my request:
export async function uploadImageToCDN(formData: FormData): Promise<ICDNUploadResponse> {
return new Promise(async (resolve, reject) => {
const token = await getApiTokenByScope('scope')
const xhr = new XMLHttpRequest()
xhr.open('post', '/api/test/files/upload')
xhr.responseType = 'json'
xhr.setRequestHeader('Authorization', `Bearer ${token}`)
xhr.onload = async () => {
if (xhr.status === 401) {
await refreshApiTokenByScope('scope')
.then(() => {
uploadImageToCDN(formData)
})
}
resolve(xhr.response)
}
xhr.onerror = () => {
reject(xhr.response)
}
xhr.send(formData)
})
}

How to upload image as binary in react native

this is from post man
in react native how can i convert image and upload it to server as binary
this is my code i try to use form data insted of header but still not working
the upload work but the image not showing
ImagePicker.showImagePicker(options, async (response) => {
if (response.didCancel) {
setIsLoading(false);
} else if (response.error) {
setIsLoading(false);
} else if (response.customButton) {
} else {
setIsLoading(true);
function dataURLtoFile(dataurl, filename) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new File([u8arr], filename, {type: mime});
}
var file = dataURLtoFile(
'data:image/png;base64,' + response.data,
'hello2.png',
);
var myHeaders = new Headers();
myHeaders.append('type', '1');
myHeaders.append('uploadPath', 'xxx');
myHeaders.append('Content-Type', 'image/png');
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: file,
processData: false,
contentType: false,
};
fetch(
'xxx',
requestOptions,
)
.then((response) => response.json())
.then((result) => {
after i upload the image this is how it show
I don't know why you convert your file to data:String, and try to upload as image/png content-type. Do you want data:string or as the file itself? if you want to use data:String then your content type should be plain/text.
This is what I normally do to upload image.
const uploadImage = async (response) => {
const put = await fetch(url, { method: 'post', body: response, headers: { "Content-type": response.type } });
}
Where response is the response returned by ImagePicker.showImagePicker
Depending on your server, you may require form data, which then you need to do the formData way.
const uploadImage = async (response) => {
let formData = new FormData();
formData.append('file', response);
//in most case you do not need to create custom header object.
const put = await fetch(url, { method: 'post', body: formData });
}
blob method.
const uploadImage = async (response) => {
var blob = new Blob(response);
//in most case you do not need to create custom header object.
const put = await fetch(url, { method: 'post', body: blob, header: { 'Content-type": response.type });
}
Above example is base on a single file selected, if you select multiple file then response will of course be an array instead.

Resources