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

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

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

react native image picker send to spring boot error

const loadLibrary = useCallback(async () => {
launchImageLibrary(
{
mediaType: 'photo',
},
response => {
if (response?.errorCode) {
console.log('LaunchImageLibrary Error: ', response.errorMessage);
} else {
console.log('response=', response.assets[0]);
const formData = new FormData();
formData.append('image', {
name: response.assets[0].fileName, // require, file name
uri: response.assets[0].uri, // require, file absoluete path
type: response.assets[0].type, // options, if none, will get mimetype from `filepath` extension
});
console.log('formData=', formData);
axios
.post('/users', formData)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
// );
}
},
);
}, [userInfo]);
spring code ---
#PostMapping(value="/api/v1/users")
public String createUser(
#RequestParam("image") MultipartFile image) {
System.out.println(image);
return "";
}
-error--
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
how to deal with?
Previously, this code worked well.
try this and let me know
const formData = new FormData();
formdata.append("image", {type: 'image/jpg', uri:response.assets[0], name:response.assets[0]});
console.log('formData=', formData);
axios
.post('/users', formData)
.then(function (response) {
console.log(response.data);
})
.catch(function (error) {
console.log(error);
});
// );
}
},
);

I get Error While uploading File Typeerror : Network Request failed, whenever I try to upload a picture to s3 bucket

The code is as follows:
const updatePhotoHandler = () => {
ImagePicker.openPicker({
width: 300,
height: 400,
cropping: true,
}).then((image) => {
console.log('image', image);
setImage(image);
setPhoto(image.path);
});
image != '' && uploadImageToAWS(image);
};
const uploadImageToAWS = async (imageFile) => {
console.log('upload image to aws', imageFile);
var files = [imageFile];
console.log('upload file to aws', files);
var fileKey = 'some key';
uploadMultipleFiles(files, fileKey, uploadSuccess, uploadError);
};
const uploadMultipleFiles = (files, fileKey, cbSuccess, cbError) => {
var baseScope = {};
baseScope.numberOfUploads = files.length;
baseScope.uploadInfo = {};
baseScope.afterUploadFileCB = cbSuccess;
for (var i in files) {
var file = files[i];
baseScope.uploadInfo[file.path] = '';
uploadFile(file, fileKey, handleFileUploadSuccess, cbError, baseScope);
}
};
const uploadFile = (file, fileKey, cbSuccess, cbError, baseScope) => {
console.log('fileeee', file);
console.log('upload filekey', fileKey);
var mimetype = getMimeType(file.mime);
console.log('mime', mimetype);
// console.log("Blob data ",encryptedDataBlob)
let awsUploadLink = `${ROOT}/get-aws-upload-signature`;
console.log('aws',awsUploadLink)
let url = new URL(awsUploadLink);
let urlParams = {mimetype: mimetype};
Object.keys(urlParams).forEach((key) =>
url.searchParams.append(key, urlParams[key]),
);
fetch(url, {
method: 'POST',
credentials: 'include',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
.then((response) => response.json())
.then((response) =>
awsSignaturePolicyResponse(
response,
file,
fileKey,
mimetype,
cbSuccess,
cbError,
baseScope,
).catch((error) => {
console.error('Error while uploading to s3 ', error);
if (cbError) {
cbError('Error while uploading file ' + error);
}
}),
);
};
const awsSignaturePolicyResponse = async (
response,
file,
fileKey,
mimetype,
cbSuccess,
cbError,
baseScope,
) => {
if (response['code'] === 200) {
console.log('file',file)
let awsSignature = response['content']['s'];
let awsPolicy = response['content']['p'];
let dataBlob = new Blob([file], {type: mimetype});
var uploadPath = fileKey + generateUniqueFileName(file.path);
let formData = new FormData();
formData.append('policy', awsPolicy);
formData.append('signature', awsSignature);
formData.append('acl', 'public-read');
formData.append('AWSAccessKeyId', AWS_ACCESS_KEY);
formData.append('key', uploadPath);
// console.log("Key is ",uploadPath);
formData.append('Content-Type', mimetype);
formData.append('file', dataBlob);
let awsFileUrl = awsS3URL + '/' + uploadPath;
let uploadUrl = awsS3URL;
fetch(uploadUrl, {
method: 'POST',
credentials: 'include',
body: formData,
})
.then((response) => cbSuccess(file.name, awsFileUrl, baseScope))
.catch((error) => {
console.error('Error while uploading to s3 ', error);
if (cbError) {
cbError('Error while uploading file ' + error);
}
});
}
};
Now whenever I try uploading the file.path to s3 I am receiving Network Request Failed.
My image object that I receive when from Image picker is as follows
Stuck since long now, if anyone could say where have I gone wrong please if anyone could help me I would be very much obliged.
Any lead would be appreciated.

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

undefined error when trying to set state

I'm trying to upload images and then set the state for each image uploaded.
However, I keep on getting this error when hitting the 'Upload' button:
catch: TypeError: Cannot read property 'setState' of undefined
The error is occurring in this block of code:
.then(function (response) {
//handle success
console.log('then: ', response);
this.setState({
file: e.target.files[0]
});
})
Any help would be appreciated!
Thanks!
Here is the entire component:
import React, { Component } from 'react';
import axios from 'axios';
class ImageUpload extends Component {
constructor(props) {
super(props);
this.state = { file: '', imagePreviewUrl: '' };
}
_handleSubmit(e) {
e.preventDefault();
let fd = new FormData();
fd.append('image', this.state.file);
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
const postData = {
method: 'POST',
credentials: 'include',
body: fd
}
axios({
method: 'post',
url: `/api/gaming/profiles/${this.props.profileId}/files/upload`,
data: postData
})
.then(function (response) {
//handle success
console.log('then: ', response);
this.setState({
file: event.target.files[0]
});
})
.catch(function (response) {
//handle error
console.log('catch: ', response);
});
}
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
render() {
const { questionId } = this.props;
let { imagePreviewUrl } = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} />);
} else {
$imagePreview = (<div className="previewText">Please select an Image for Preview</div>);
}
console.log('ImageUpload Render()');
return (
<div className="previewComponent">
<input className="fileInput"
type="file"
onChange={(e) => this._handleImageChange(e)} />
<button className="submitButton"
type="submit"
onClick={(e) => this._handleSubmit(e)}>Upload Image</button>
<div className="imgPreview">
{$imagePreview}
</div>
</div>
);
}
}
export default ImageUpload;
Change your Promise resolver to an arrow function, it'll lexically scope this for you.
Change it to:
.then((response) => {
//handle success
console.log('then: ', response);
this.setState({
file: e.target.files[0]
});
})
In your _handleSubmit(e) define var self = this
then use self.setState instead of this.setState
_handleSubmit(e) {
e.preventDefault();
let fd = new FormData();
fd.append('image', this.state.file);
const config = {
headers: { 'content-type': 'multipart/form-data' }
}
const postData = {
method: 'POST',
credentials: 'include',
body: fd
}
var self = this
axios({
method: 'post',
url: `/api/gaming/profiles/${this.props.profileId}/files/upload`,
data: postData
})
.then(function (response) {
//handle success
console.log('then: ', response);
self.setState({
file: event.target.files[0]
});
})
.catch(function (response) {
//handle error
console.log('catch: ', response);
});
}

Resources