How to make file upload in React - reactjs

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..?

Related

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 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.

React js quill image upload

I am trying to upload my image to the server by manually changing the Quill image upload function. Here is the error i get (by the way, there is no error related to API!), however I am stuck on it for couple of hours.
User trying to upload this: File {name: "rolling_pin.png", lastModified: 1588035813056, lastModifiedDate: Tue Apr 28 2020 04:03:33 GMT+0300, webkitRelativePath: "", size: 1289850, …}
quill.js:214 POST https://smartquestionapi.advancity.net/image 400
(anonymous) # quill.js:214
quill.js:228 {error: true, response: 400, "rsponse: ": ""}
undefined:1 GET https://smartquestionapi.advancity.net/Images/undefined 404
Here is my code:
function imageHandler() {
/*
DEFAULT UPLOAD BY LINK
var range = this.quill.getSelection();
var value = prompt('What is the image URL');
if (value) {
this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
}*/
const input = document.createElement('input');
input.setAttribute('type', 'file');
input.setAttribute('accept', 'image/*');
input.click();
input.onchange = async function () {
const file = input.files[0];
console.log('User trying to upload this:', file);
const formData = new FormData()
if (file !== null) {
formData.append('file', file)
}
fetch('https://smartquestionapi.advancity.net/image', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(function (response) {
if (response.ok) {
return response.json()
} else {
return { "error": true,'response':response.status, 'rsponse: ':response.statusText }
}
}).then((json) => {
console.log(json)
var cursorPosition = this.quill.getSelection();
var imagePath = "https://smartquestionapi.advancity.net/Images/" + json.imageUrl;
this.quill.insertEmbed(cursorPosition.index, 'image', imagePath, Quill.sources.USER);
return json;
}).catch(err => {
console.log("eror: ", err);
})
}.bind(this);
}
Change the file to files instead
if (file !== null) {
formData.append('files', file)
}

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

Picking up document/Images from mobile device and show them into a list in react native

I am using react native document picker library to upload documents to the server my code is working perfectly but the issue is i want to show list of these selected images/documents i am not sure how to perform that action here is my code....
Document Selection code:
pickMultiple() {
try {
DocumentPicker.pickMultiple({
})
.then(images => {
this.setState({
image: null,
images: images
});
//console.log(images.length);
})
.catch(e => alert(e));
} catch (err) {
if (DocumentPicker.isCancel(err)) {
// User cancelled the picker, exit any dialogs or menus and move on
} else {
throw err;
}
}
}
Form Uploading code:
SubmitProposal = async () => {
const Uid = await AsyncStorage.getItem("projectUid");
const { params } = this.props.navigation.state;
const { amount, Description, DurationListKnown, images } = this.state;
console.log(
amount,
Description,
DurationListKnown[0],
images,
params.job_id,
images.length,
Uid
);
const formData = new FormData();
formData.append('user_id' , Uid);
formData.append('project_id' , params.job_id);
formData.append('proposed_amount' , amount);
formData.append('proposed_time' , DurationListKnown[0]);
formData.append('proposed_content' , Description);
formData.append('size' , images.length);
//formData.append('proposal_files' , images);
images.forEach((item, i) => {
// propertyData.description = this.props.description
var path = item.uri;
// var filename = path.substring(path.lastIndexOf('/')+1);
var filename = item.name;
formData.append("proposal_files"+i, {
uri: path,
type: item.type,
name: filename || `filename${i}.jpg`,
});
});
console.log(formData);
fetch('https://...proposal/add_proposal',{
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(response => {
if (response.status == "200") {
console.log(response);
this.showSuccessAlert();
} else if (response.status == "203") {
console.log(response);
this.showAlert();
}
}).catch((error) => {
console.log(JSON.stringify( error));
});
};
kindly help me about how can i show list of these images/documents

Resources