Upload images from iOS is too slow - node.js

My React-Native iOS front-end can not upload images to my Node.JS (Express + Multer) back-end.
My front-end is React Native Android & iOS. The Android version works fine with no issues, however, uploading images from and iOS device doesn't work most of the time.
Once the upload request is sent, I can see the image file is added in FTP, however, very slowly, like a few KB every second. An image of 500 KB may take 3 minutes or more till the request times out. The file is added to the server partially and I can see change in size with each refresh.
Some [iOS] devices had no issues at all, uploads fast, however, the vast majority of devices are running into this issue.
No connectivity issues. The same host and network work perfectly with Android. Same with some iOS devices.
This is not limited to a specific iOS version or device. However, the devices who had the issue always have it, and those that don't, never have it.
How can I troubleshoot this?
POST request:
router.post('/image', (req, res) => {
console.log('image')
upload(req, res, (error) => {
if (error) {
console.log(error)
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'Invalid file type. Only JPG, PNG or GIF file are allowed.'
}));
} else {
if (req.file == undefined) {
console.log('un')
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'File size too large'
}));
} else {
var CaseID = req.body._case; // || new mongoose.Types.ObjectId(); //for testing
console.log(req.body._case + 'case')
var fullPath = "uploads/images/" + req.file.filename;
console.log(fullPath);
var document = {
_case: CaseID,
path: fullPath
}
var image = new Image(document);
image.save(function(error) {
if (error) {
console.log(error)
return res.send(JSON.stringify({
data: [],
state: 400,
message: 'bad request error'
}));
}
return res.send(JSON.stringify({
data: image,
state: 200,
message: 'success'
}));
});
}
}
});
});
Upload.js:
const multer = require('multer');
const path = require('path');
//image upload module
const storageEngine = multer.diskStorage({
destination: appRoot + '/uploads/images/',
filename: function (req, file, fn) {
fn(null, new Date().getTime().toString() + '-' + file.fieldname + path.extname(file.originalname));
}
});
const upload = multer({
storage: storageEngine,
// limits: {
// fileSize: 1024 * 1024 * 15 // 15 MB
// },
fileFilter: function (req, file, callback) {
validateFile(file, callback);
}
}).single('image');
var validateFile = function (file, cb) {
// allowedFileTypes = /jpeg|jpg|png|gif/;
// const extension = allowedFileTypes.test(path.extname(file.originalname).toLowerCase());
// const mimeType = allowedFileTypes.test(file.mimetype);
// if (extension && mimeType) {
// return cb(null, true);
// } else {
// cb("Invalid file type. Only JPEG, PNG and GIF file are allowed.")
// }
var type = file.mimetype;
var typeArray = type.split("/");
if (typeArray[0] == "image") {
cb(null, true);
}else {
cb(null, false);
}
};
module.exports = upload;
React Native Upload function:
pickImageHandler = () => {
ImagePicker.showImagePicker(this.options1, res => {
if (res.didCancel) {
} else if (res.error) {
} else {
this.setState({upLoadImage:true})
var data = new FormData();
data.append('image', {
uri: res.uri,
name: 'my_photo.jpg',
type: 'image/jpg'
})
data.append('_case',this.state.caseID)
fetch(url+'/image'
, {method:'POST',
body:data
}
)
.then((response) => response.json())
.then((responseJson) =>
{
this.setState(prevState => {
return {
images: prevState.images.concat({
key: responseJson._id,
src: res.uri
})
}
}
)
this.setState({upLoadImage:false})
})
.catch((error) =>
{
alert(error);
});
}
}
)
}
Any suggestions?
Thanks

I saw your answer from UpWork
please try this way,
I'm using API Sauce for API calls
export const addPartRedux = (data) => {
return (dispatch, getState) => {
console.log('addPArtREdux', data);
const values = {
json_email: data.token.username,
json_password: data.token.password,
name: data.text ? data.text : '',
car: data.selected.ID,
model: data.selectedSub.ID,
make_year: data.selectedYear,
type: data.type,
ImportCountry: data.import_image ? data.import_image : '',
FormNumber: data.number ? data.number : '',
do: 'insert'
};
const val = new FormData();
Object.keys(values).map((key) =>
val.append(key, values[key])
);
if (data.imageok) {
val.append('image', {
uri: data.image.uri,
type: data.image.type,
name: data.image.name
});
}
dispatch(loading());
api
.setHeader('Content-Type', 'multipart/form-data;charset=UTF-8');
api
.post('/partRequest-edit-1.html?json=true&ajax_page=true&app=IOS',
val,
{
onUploadProgress: (e) => {
console.log(e);
const prog = e.loaded / e.total;
console.log(prog);
dispatch(progress(prog));
}
})
.then((r) => {
console.log('Response form addPartRedux', r.data);
if (r.ok === true) {
const setting = qs.parse(r.data);
dispatch(addpart(setting));
} else {
dispatch(resetLoading());
dispatch(partstError('Error Loading '));
}
})
.catch(
(e) => {
console.log('submitting form Error ', e);
dispatch(resetLoading());
dispatch(partstError('Try Agin'));
}
);
};
};

Related

Upload Image data showing {} in Nodejs from ANgular js

I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {}
Pleasse see images
enter image description here
enter image description here
const imageUpload = multer({
storage: multer.diskStorage({
destination: function (req, file, cb) {
console.log("asd");
cb(null, "Attachments/");
},
filename: function (req, file, cb) {
cb(null, new Date().valueOf() + "_" + file.originalname);
},
}),
limits: { fileSize: 10000000 },
fileFilter: function (req, file, cb) {
if (
!file.originalname.match(
/\.(jpg|JPG|webp|jpeg|JPEG|png|PNG|gif|GIF|pdf|PDF|docx|doc)$/
)
) {
req.fileValidationError = "Only Image, PDF and Word files are allowed!";
return cb(null, false);
} else {
req.fileValidationError = "";
}
cb(null, true);
},
});
---
// Add Property Details
app.post('/addproperty', imageUpload.single("image"), (req, res) => {
console.log("vicky", req.body.body.file);
if (req.fileValidationError != "") {
throw req.fileValidationError;
}
console.log(req.body.body)
req.body.body = req.body;
let qrr = 'INSERT INTO listproperty (Type, plotNo, location, sqft, sellType, facing, price, BedRoom, BAthRoom, Parking, date, Description, src)VALUES("'+req.body.Type+'","'+req.body.plotNo+'","'+req.body.location+'","'+req.body.sqft+'","'+req.body.sellType+'","'+req.body.facing+'", "'+req.body.price+'","'+req.body.BedRoom+'","'+req.body.BAthRoom+'","'+req.body.Parking+'","'+req.body.date+'","'+req.body.Description+'","'+req.body.src+'");'
db.query(qrr, (err1, res1) => {
if(err1)console.log(err1);
else {
res.send({
message: 'Data inserted',
body:res1
})
}
})
});
newProperty : any = new FormGroup({
Type: new FormControl([Validators.required]),
sellType: new FormControl([Validators.required]),
facing: new FormControl([Validators.required]),
src: new FormControl(''),
plotNo: new FormControl('', Validators.required),
location: new FormControl('', Validators.required),
price: new FormControl(Validators.required),
sqft: new FormControl(Validators.required),
BedRoom: new FormControl(Validators.required),
BAthRoom: new FormControl(Validators.required),
Parking: new FormControl(Validators.required),
Description: new FormControl('', Validators.required),
date: new FormControl([Validators.required]),
});
// On file Select
onChange(event: any) {
this.newProperty.value.src = event.target.files;
//console.log(event);
// this.file = event.target.files[0];
}
ngOnInit(): void {
this.getPropertyType()
this.sellType = this.data.getSellType();
let x = this.route.snapshot.paramMap.get('property')
// if (x) {
// var d=this.data.getSingleData(x)
// console.log(d);
// setTimeout(() => {
// this.newProperty.patchValue(d)
// // this.newProperty.setControl('src')
// }, 1000);
// }
}
getPropertyType() {
console.log("res", this.sql.getPlotType());
this.sql.getPlotType().subscribe((res)=>{
console.log(res);
for (let i = 0; i < res.length; i++) {
this.plotType.push( res[i].propertyType);
}
// this.plotType =res
});
}
addNew() {
if (this.newProperty.invalid) {
alert('fill all details');
return;
}
var data = [];
//JSON.parse(this.newProperty.value)
this.sql.addplotdata(this.newProperty.value).subscribe((res)=>{
console.log(res);
for (let i = 0; i < res.length; i++) {
data.push( res);
}
console.log("data");
// this.plotType =res
});
console.log(this.newProperty.value);
// this.data.addData(this.newProperty.value);
//this.newProperty.reset();
this.router.navigate(['add-property']);
}
addplotdata(value: any): Observable<any> {
return this.http.post(this.addPropUrl, {value, "image" :value.src});
} // Backend.ts
Hello, I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {} Pleasse see images
Hello, I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {} Pleasse see images
Hello, I am wrking on nodejs . i got response from frontend post request. all dataa is getting but upload file data showing null. {} Pleasse see images

AWS S3 Angular 14 with Nodejs - Multi Part Upload sending the same ETag for every part

AWS S3 Angular 14 with Nodejs - Multi Part Upload sending the same ETag for every part
Backend Nodejs Controller Looks Like -
const AWS = require('aws-sdk');
const S3 = new AWS.S3({
// endpoint: "http://bucket.analysts24x7.com.s3-website-us-west-1.amazonaws.com",
// accessKeyId: S3_KEY,
// secretAccessKey: S3_SECRET,
// region: process.env.POOL_REGION,
apiVersion: '2006-03-01',
signatureVersion: 'v4',
// maxRetries: 10
});
exports.startUpload = (req, res) => {
try {
const filesData = JSON.parse(JSON.stringify(req.files));
const eachFiles = Object.keys(filesData)[0];
console.log(filesData[eachFiles]);
let params = {
Bucket: process.env.STORE_BUCKET_NAME,
Key: filesData[eachFiles].name,
// Body: Buffer.from(filesData[eachFiles].data.data, "binary"),
ContentType: filesData[eachFiles].mimetype
// ContentType: filesData[eachFiles].data.type
};
return new Promise((resolve, reject) => {
S3.createMultipartUpload(params, (err, uploadData) => {
if (err) {
reject(res.send({
error: err
}));
} else {
resolve(res.send({ uploadId: uploadData.UploadId }));
}
});
});
} catch(err) {
res.status(400).send({
error: err
})
}
}
exports.getUploadUrl = async(req, res) => {
try {
let params = {
Bucket: process.env.STORE_BUCKET_NAME,
Key: req.body.fileName,
PartNumber: req.body.partNumber,
UploadId: req.body.uploadId
}
return new Promise((resolve, reject) => {
S3.getSignedUrl('uploadPart', params, (err, presignedUrl) => {
if (err) {
reject(res.send({
error: err
}));
} else {
resolve(res.send({ presignedUrl }));
}
});
})
} catch(err) {
res.status(400).send({
error: err
})
}
}
exports.completeUpload = async(req, res) => {
try {
let params = {
Bucket: process.env.STORE_BUCKET_NAME,
Key: req.body.fileName,
MultipartUpload: {
Parts: req.body.parts
},
UploadId: req.body.uploadId
}
// console.log("-----------------")
// console.log(params)
// console.log("-----------------")
return new Promise((resolve, reject) => {
S3.completeMultipartUpload(params, (err, data) => {
if (err) {
reject(res.send({
error: err
}));
} else {
resolve(res.send({ data }));
}
})
})
} catch(err) {
res.status(400).send({
error: err
})
};
}
FrontEnd Angular 14 Code --
uploadSpecificFile(index) {
const fileToUpload = this.fileInfo[index];
const formData: FormData = new FormData();
formData.append('file', fileToUpload);
this.shared.startUpload(formData).subscribe({
next: (response) => {
const result = JSON.parse(JSON.stringify(response));
this.multiPartUpload(result.uploadId, fileToUpload).then((resp) => {
return this.completeUpload(result.uploadId, fileToUpload, resp);
}).then((resp) => {
console.log(resp);
}).catch((err) => {
console.error(err);
})
},
error: (error) => {
console.log(error);
}
})
}
multiPartUpload(uploadId, fileToUpload) {
return new Promise((resolve, reject) => {
const CHUNKS_COUNT = Math.floor(fileToUpload.size / CONSTANTS.CHUNK_SIZE) + 1;
let promisesArray = [];
let params = {};
let start, end, blob;
for (let index = 1; index < CHUNKS_COUNT + 1; index++) {
start = (index - 1) * CONSTANTS.CHUNK_SIZE
end = (index) * CONSTANTS.CHUNK_SIZE
blob = (index < CHUNKS_COUNT) ? fileToUpload.slice(start, end) : fileToUpload.slice(start);
// blob.type = fileToUpload.type;
params = {
fileName: fileToUpload.name,
partNumber: index,
uploadId: uploadId
}
console.log("Start:", start);
console.log("End:", end);
console.log("Blob:", blob);
this.shared.getUploadUrl(params).subscribe({
next: (response) => {
const result = JSON.parse(JSON.stringify(response));
// Send part aws server
const options = {
headers: { 'Content-Type': fileToUpload.type }
}
let uploadResp = axios.put(result.presignedUrl, blob, options);
promisesArray.push(uploadResp);
if(promisesArray.length == CHUNKS_COUNT) {
resolve(promisesArray)
}
},
error: (error) => {
console.log(error);
reject(error);
}
})
}
})
}
async completeUpload(uploadId, fileToUpload, resp) {
let resolvedArray = await Promise.all(resp)
let uploadPartsArray = [];
console.log("I am etag -----");
console.log(resolvedArray);
resolvedArray.forEach((resolvedPromise, index) => {
uploadPartsArray.push({
ETag: resolvedPromise.headers.etag,
PartNumber: index + 1
})
})
// Complete upload here
let params = {
fileName: fileToUpload.name,
parts: uploadPartsArray,
uploadId: uploadId
}
return new Promise((resolve, reject) => {
this.shared.completeUpload(params).subscribe({
next: (response) => {
resolve(response);
},
error: (error) => {
reject(error);
}
})
})
}
What I am trying to do --
Initiate a multipart upload ( API - /start-upload ) --> to get the uploadId
Upload the object’s parts ( API - /get-upload-url ) --> to get the presignedUrl
Call the Presigned URL and put blob as part --- To get the Etag
Complete multipart upload ( API - /complete-upload ) --> to send the complete parts.
**Sample Example of code --- **
FrontEnd --
https://github.com/abhishekbajpai/aws-s3-multipart-upload/blob/master/frontend/pages/index.js
BackEnd --
https://github.com/abhishekbajpai/aws-s3-multipart-upload/blob/master/backend/server.js
Attach the screenshot below how the API call looks like --
Now the problem here, Each and everytime I am getting same Etag from the -- above 3 steps while I am calling presignedURL using Axios. For that reason, I am getting the error in the final upload ---
Your proposed upload is smaller than the minimum allowed size
**Note --
**
Each and every chuck size I am uploading
CHUNK_SIZE: 5 * 1024 * 1024, // 5.2 MB
Apart from last part.
Also all the API are giving success response, apart from /complete-upload. Because all the API giving same Etag.
Same question also asked here, but there are no solutions --
https://github.com/aws/aws-sdk-java/issues/2615
Any idea about this ? How to resolve it ?
This is so uncommon problem, Provide me the solution of the problem.

Get progress of firebase admin file upload

I'm trying to get the progress of a 1 minute video uploading to firebase bucket storage using the admin sdk. I've seen a lot about using firebase.storage().ref.child..... but I'm unable to do that with the admin sdk since they don't have the same functions. This is my file upload:
exports.uploadMedia = (req, res) => {
const BusBoy = require('busboy');
const path = require('path');
const os = require('os');
const fs = require('fs');
const busboy = new BusBoy({ headers: req.headers, limits: { files: 1, fileSize: 200000000 } });
let mediaFileName;
let mediaToBeUploaded = {};
busboy.on('file', (fieldname, file, filename, encoding, mimetype) => {
if(mimetype !== 'image/jpeg' && mimetype !== 'image/png' && mimetype !== 'video/quicktime' && mimetype !== 'video/mp4') {
console.log(mimetype);
return res.status(400).json({ error: 'Wrong file type submitted, only .png, .jpeg, .mov, and .mp4 files allowed'})
}
// my.image.png
const imageExtension = filename.split('.')[filename.split('.').length - 1];
//43523451452345231234.png
mediaFileName = `${Math.round(Math.random()*100000000000)}.${imageExtension}`;
const filepath = path.join(os.tmpdir(), mediaFileName);
mediaToBeUploaded = { filepath, mimetype };
file.pipe(fs.createWriteStream(filepath));
file.on('limit', function(){
fs.unlink(filepath, function(){
return res.json({'Error': 'Max file size is 200 Mb, file size too large'});
});
});
});
busboy.on('finish', () => {
admin
.storage()
.bucket()
.upload(mediaToBeUploaded.filepath, {
resumable: false,
metadata: {
metadata: {
contentType: mediaToBeUploaded.mimetype
}
}
})
.then(() => {
const meadiaUrl = `https://firebasestorage.googleapis.com/v0/b/${config.storageBucket}/o/${mediaFileName}?alt=media`;
return res.json({mediaUrl: meadiaUrl});
})
.catch((err) => {
console.error(err);
return res.json({'Error': 'Error uploading media'});
});
});
req.pipe(busboy);
}
This works okay right now, but the only problem is that the user can't see where their 1 or 2 minute video upload is at. Currently, it's just a activity indicator and the user just sits their waiting without any notice. I'm using react native on the frontend if that helps with anything. Would appreciate any help!
I was able to implement on the client side a lot easier... but it works perfect with image and video upload progress. On the backend, I was using the admin sdk, but frontend I was originally using the firebase sdk.
this.uploadingMedia = true;
const imageExtension = this.mediaFile.split('.')[this.mediaFile.split('.').length - 1];
const mediaFileName = `${Math.round(Math.random()*100000000000)}.${imageExtension}`;
const response = await fetch(this.mediaFile);
const blob = await response.blob();
const storageRef = storage.ref(`${mediaFileName}`).put(blob);
storageRef.on(`state_changed`,snapshot=>{
this.uploadProgress = (snapshot.bytesTransferred/snapshot.totalBytes);
}, error=>{
this.error = error.message;
this.submitting = false;
this.uploadingMedia = false;
return;
},
async () => {
storageRef.snapshot.ref.getDownloadURL().then(async (url)=>{
imageUrl = [];
videoUrl = [url];
this.uploadingMedia = false;
this.submitPost(imageUrl, videoUrl);
});
});
export const uploadFile = (
folderPath,
fileName,
file,
generateDownloadURL = true,
updateInformationUploadProgress
) => {
return new Promise((resolve, reject) => {
try {
const storageRef = firebaseApp.storage().ref(`${folderPath}/${fileName}`)
const uploadTask = storageRef.put(file)
uploadTask.on(
'state_changed',
snapshot => {
if (updateInformationUploadProgress) {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
updateInformationUploadProgress({
name: fileName,
progress: progress,
})
}
},
error => {
console.log('upload error: ', error)
reject(error)
},
() => {
if (generateDownloadURL) {
uploadTask.snapshot.ref
.getDownloadURL()
.then(url => {
resolve(url)
})
.catch(error => {
console.log('url error: ', error.message)
reject(error)
})
} else {
resolve(uploadTask.snapshot.metadata.fullPath)
}
}
)
} catch (error) {
reject(error)
}
})
}

How to upload image files in Postman and echo back the same image using Express and Multer

I am trying to upload a product using postman and anytime I submit; it sends back all the data with the image undefined as shown in this screenshot:
My controller file:
const gameRepository = require("../routes/repository")
exports.createGame = async (req, res, next) => {
try {
const PORT = 8000;
const hostname = req.hostname;
const url = req.protocol + '://' + hostname + ':' + PORT + req.path;
const payload = ({
name: req.body.name,
price: req.body.price,
category: req.body.category,
gameIsNew: req.body.gameIsNew,
topPrice: req.body.topPrice,
isVerOrient: req.body.IsVerOrient,
description: req.body.description,
image: url + '/imgs/' + req.path
});
let eachGame = await gameRepository.createGame({
...payload
});
console.log(req.body)
res.status(200).json({
status: true,
data: eachGame,
})
} catch (err) {
console.log(err)
res.status(500).json({
error: err,
status: false,
})
}
}
repository.js:
const Game = require("../models/gameModel");
exports.games = async () => {
const games = await Game.find();
return games;
}
exports.gameById = async id => {
const game = await Game.findById(id);
return game;
}
exports.createGame = async payload => {
const newGame = await Game.create(payload);
return newGame;
}
exports.removeGame = async id => {
const game = await Game.findById(id);
return game;
}
Multer.js:
const multer = require("multer");
const path = require("path");
// checking for file type
const MIME_TYPES = {
'imgs/jpg': 'jpg',
'imgs/jpeg': 'jpeg',
'imgs/png': 'png'
}
// Image Upload
const storage = multer.diskStorage({
destination: (req, file, cb ) => {
cb(null, path.join('../imgs'));
},
filename: (req, file, cb) => {
const name = file.originalname.split('').join(__);
const extension = MIME_TYPES[file.mimetype];
cb(null, name + new Date().toISOString() + '.' + extension);
}
});
module.exports = multer({
storage: storage,
limits: {
fileSize: 1024 * 1024 * 6
},
})
I am not sure about where I went wrong, that is why I need an external eye to help locate where the fault is coming from.
I have a feeling that I need to use body-parser or navigate into the image folder correctly, or multi-part form, I am not sure.
after many try and fail I finally figured it out.
turns out it has compatibility issues depending on your OS.
I use windows 10 and this resolved the issue for me
Here is my working code:
multer.js
const multer = require("multer");
const path = require("path");
// checking for file type
const MIME_TYPES = {
'image/jpg': 'jpg',
'image/jpeg': 'jpeg',
'image/png': 'png'
}
// Image Upload
const storage = multer.diskStorage({
destination: (req, file, cb ) => {
cb(null, ('storage/imgs/'));
},
filename: (req, file, cb) => {
const extension = MIME_TYPES[file.mimetype];
// I added the colons in the date of my image with the hyphen
cb(null, `${new Date().toISOString().replace(/:/g,'-')}.${extension}`);
}
});
module.exports = multer({
storage: storage
})
In my controller.js
const gameRepository = require("../routes/repository");
exports.createGame = async (req, res, next) => {
try {
const payload = {
name: req.body.name,
price: req.body.price,
category: req.body.category,
gameIsNew: req.body.gameIsNew,
topPrice: req.body.topPrice,
isVerOrient: req.body.IsVerOrient,
description: req.body.description,
image: req.file.filename,
};
let eachGame = await gameRepository.createGame({
...payload,
});
res.status(200).json({
status: true,
data: eachGame,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
status: false,
});
}
};
exports.getGames = async (req, res) => {
try {
let games = await gameRepository.games();
res.status(200).json({
status: true,
data: games,
});
} catch (err) {
console.log(err);
res.status(500).json({
error: err,
status: false,
});
}
};
exports.getGameById = async (req, res) => {
try {
let id = req.params.id;
let gameDetails = await gameRepository.gameById(id);
req.req.status(200).json({
status: true,
data: gameDetails,
});
} catch (err) {
res.status(500).json({
status: false,
error: err,
});
}
};
exports.removeGame = async (req, res) => {
try {
let id = req.params.id;
let gameDetails = await gameRepository.removeGame(id);
res.status(200).json({
status: true,
data: gameDetails,
});
} catch (err) {
res.status(500).json({
status: false,
data: err,
});
}
};
:
Postman output
Thanks to this great community.

How to send selected files to a node server using react native fs?

I am using https://github.com/itinance/react-native-fs to upload files from a react-native client, but it's not getting received in my nodejs server. By the way, I have used react-native-document-picker https://github.com/Elyx0/react-native-document-picker to select the files from the Android file system. Here is my client app's code;
async uploadToNode() {
let testUrl = this.state.multipleFile[0].uri; //content://com.android.providers.media.documents/document/image%3A7380
const split = testUrl.split('/');
const name = split.pop();
const setFileName = "Img"
const inbox = split.pop();
const realPath = `${RNFS.TemporaryDirectoryPath}${inbox}/${name}`;
const uploadUrl = "http://localhost:8082/uploadToIpfs";
var uploadBegin = (response) => {
const jobId = response.jobId;
console.log('UPLOAD HAS BEGUN! JobId: ' + jobId);
};
var uploadProgress = (response) => {
const percentage = Math.floor((response.totalBytesSent/response.totalBytesExpectedToSend) * 100);
console.log('UPLOAD IS ' + percentage + '% DONE!');
};
RNFS.uploadFiles({
toUrl: uploadUrl,
files: [{
name: setFileName,
filename:name,
filepath: realPath,
}],
method: 'POST',
headers: {
'Accept': 'application/json',
},
begin: uploadBegin,
beginCallback: uploadBegin, // Don't ask me, only way I made it work as of 1.5.1
progressCallback: uploadProgress,
progress: uploadProgress
})
.then((response) => {
console.log(response,"<<< Response");
if (response.statusCode == 200) { //You might not be getting a statusCode at all. Check
console.log('FILES UPLOADED!');
} else {
console.log('SERVER ERROR');
}
})
.catch((err) => {
if (err.description) {
switch (err.description) {
case "cancelled":
console.log("Upload cancelled");
break;
case "empty":
console.log("Empty file");
default:
//Unknown
}
} else {
//Weird
}
console.log(err);
});
}
I'm not sure if the nodejs code is correct to get the files from the client app. And here is my Server code;
app.post('/uploadToIpfs', (req, res) => {
// network.changeCarOwner(req.body.key, req.body.newOwner)
// .then((response) => {
// res.send(response);
// });
// var fileName = "Img";
// if(req.name == fileName){
// console.log(req.filename);
// res.send("Passed")
// }else{
// res.send("failed")
// }
console.log(req.files[0].filename);
res.send("Passed")
});
app.listen(process.env.PORT || 8082);

Resources