React js quill image upload - reactjs

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

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

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.

Pick images in react native and upload it

I want to upload an array of images using react-native-image-crop-picker but I can't fix it.
What I've tried:
Fetch (javascript) and also RN-fetch-blob but no luck
At first the catch error was network error
and now the problem is that I'm sending an empty array to the server
here is my code:
export default class Upload extends Component {
constructor() {
super();
this.state = {
token: '',
photos: [],
};
}
_TakePhoto() {
ImagePicker.openPicker({
multiple: true,
}).then((images) => {
images.map((item, index) => {
ImageResizer.createResizedImage(item.path, 1200, 1200, 'JPEG', 100)
.then((response) => {
// console.warn('Resized img is: ', response);
this.state.photos.push(response);
console.warn('Resized img state is: ', this.state.photos);
this._submit_pictures();
})
.catch((err) => {});
});
});
}
_submit_pictures() {
let formData = new FormData();
for (let i = 0; i < this.state.photos.length; i++) {
let file = {
uri: this.state.photos[0].path,
// uri: this.state.photos[0].path.replace('file:///', ''),
// uri: this.state.photos[0].uri,
type: this.state.photos[0].mime,
name: this.state.photos[0].name,
};
formData.append('pics[]', file);
}
// uri: this.state.photos[0].uri.replace("file:///", "file://"),
formData.append('postId', postId);
formData.append('token', token);
console.log('formData value: ', formData);
axios({
url: 'https://rahnama.com/webservice/submitPictures',
method: 'POST',
headers: {
// "Accept": "application/json",
'Content-Type': 'multipart/form-data',
},
// formData
body: formData,
})
.then((response) => {
console.warn('upload res: ', response);
})
.catch((error) => console.warn('upload err: ', error.response.request._response));
}
render() {
return <Text onPress={() => this._TakePhoto()}> Pick </Text>;
}
}
Solved it by sending the image data in base64.
1- Pick the image
2- convert it to base64
3- pass the base64 string as the payload

Can't send image to azure API

I'm making OCR app using amazon. App I'm doing using react native. And I have an error on the moment when I send data.
Error:
{
"code": "InvalidImageUrl",
"requestId": "c495b0d7-a65a-4138-97a9-2b1cb25dced8",
"message": "Image URL is badly formatted."
}
Why? What am I doing wrong? Code:
// ...
selectImage() {
ImagePicker.showImagePicker(options, (response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log('User tapped custom button: ', response.customButton);
} else {
const source = { uri: response.uri };
this.setState({ imageSource: source });
this.extractText(response.uri);
}
});
}
extractText = async (imageSource) => {
// alert(imageSource)
let subscriptionKey = ['CODE'];
let endpoint = ['ENDPOINT']
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
// Request parameters.
// Display the image.
var sourceImageUrl = imageSource;
const data = new FormData();
data.append(imageSource);
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: '{"url": ' + '"' + data + '"}',
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
};
}
export default ImagePickerScreen;
Based on your code,there is something wrong with your data,it should an image URL so that Azure Version service can access it . I am not quite sure that how you get data in your custom logic . But anyway , this snippet below works , pls have a try :
const data = 'https://stanstroage.blob.core.windows.net/container2/personPic.jpg';
let subscriptionKey = '<key>';
let endpoint = '<endpoint>';
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/json',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: '{"url": ' + '"' + data + '"}',
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
Result:
If you want to upload a local image, you should use application/octet-stream as request content-type and set image content buffer as request body.
You can use react-native-fs to read your local image content and use buffer to get image content buffer and post it to Azure side , try snippet below below :
let subscriptionKey = '<key>';
let endpoint = '<endpoint>';
let fileUri = '<fileUri>';
let base64 = await fs.readFile(fileUri, 'base64');
let data = Buffer.from(base64, 'base64');
console.log(data);
if (!subscriptionKey) { throw new Error('Set your environment variables for your subscription key and endpoint.'); }
var uriBase = endpoint + "vision/v2.1/ocr";
fetch(uriBase + "?" + {
"language": "unk",
"detectOrientation": "true",
},
{
method: 'POST',
headers:
{
'Content-Type': 'application/octet-stream',
'Ocp-Apim-Subscription-Key': subscriptionKey,
},
body: data,
}).then((response) => response.json()).then((data) =>
{
console.log(JSON.stringify(data, null, 2));
}).catch((error) =>
{
console.log(error);
});
Result :

How to put base64 video Url on amazon s3 url usign axios

I have tried following code, please take this as example
var options = { headers: { 'Content-Type': 'media/mp4' }};
var video_buffer = new Buffer(videoBase64string);
var data = {
Key: signedVideoKey,
Body: video_buffer,
ContentEncoding: 'base64'
};
axios.put(signedVideoUrl, data, options).then((resp) => {
alert('Video has been uploaded.')
}
Here is an complete example how to upload my files on S3 signed url. Here i realized that we don't need to upload base64url just completely upload file without encoding.
Many thanks to Medium. Here you can read more about this
https://medium.com/#kevinwu/client-side-file-upload-to-s3-using-axios-c9363ec7b530
var React = require('react');
var Dropzone = require('react-dropzone');
var axios = require('axios');
exports = module.exports = React.createClass({
_onDrop: function (files) {
var file = files[0];
axios.get(ENDPOINT_TO_GET_SIGNED_URL, {
filename: file.name,
filetype: file.type
})
.then(function (result) {
var signedUrl = result.data.signedUrl;
var options = {
headers: {
'Content-Type': file.type
}
};
return axios.put(signedUrl, file, options);
})
.then(function (result) {
console.log(result);
})
.catch(function (err) {
console.log(err);
});
},
render: function () {
return (
<Dropzone onDrop={ this._onDrop } size={ 150 }>
<div>
Drop some files here!
</div>
</Dropzone>
);
}
});

Resources