Dropbox javascript api show error: TypeError: Failed to fetch - dropbox

I have a problem when uploading file using dropbox api for javacript. Sometime it's done but something it shows error: "TypeError: Failed to fetch" and cannot upload. Can anyone have experience about this error? Thanks in advance.
Here is my page source in Asp.Net:
var dbx = new Dropbox.Dropbox({ accessToken: 'MY_TOKEN' });
var fileInput = document.getElementById('file-upload'); //$('#file-upload');
var filecontent = fileInput.files[0];
var filename = fileInput.files[0].name;//.match(/([^\\\/]+)$/)[0];
if (fileInput.files[0].size < UPLOAD_FILE_SIZE_LIMIT) { // File is smaller than 150 Mb - use filesUpload API
dbx.filesUpload({ path: '/' + filename, contents: filecontent, mode: 'overwrite', autorename: false, mute: false })
.then(function (response) {
alert('success');
console.log(response);
})
.catch(function (error) {
alert(error.name);
console.error(error);
});

Related

Upload file via #aws-sdk/client-s3 and graphql-upload

S3('#aws-sdk/client-s3') upload function
import { Upload } from '#aws-sdk/lib-storage';
async s3UploadPhoto(fileStream, name, mimetype) {
const fileKey = this.getFileKey(name);
const sendParams: PutObjectCommandInput = {
Bucket: process.env.AWS_BUCKET_NAME,
Body: fileStream,
Key: fileKey,
ContentType: mimetype,
};
try {
const parallelUploads3 = new Upload({
client: this.s3,
tags: [],
queueSize: 4,
leavePartsOnError: false,
params: sendParams,
});
parallelUploads3.on('httpUploadProgress', (progress) => {
console.log(progress);
});
return parallelUploads3.done();
} catch (e) {
throw new BadRequestException('');
}
}
And Graphql upload code via 'graphql-upload'
const fileStream = file.createReadStream();
await this.s3Service.s3UploadPhoto(
fileStream,
file.filename,
file.mimetype,
);
I get error: ReferenceError: ReadableStream is not defined
If uploads a file to s3 without lib-storage, I get error: Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from #aws-sdk/lib-storage.
What is wrong written that I get error "ReadableStream is not defined"?

React Native Image Upload with FormData to NestJS server using a FileInterceptor, but 'file' is undefined

My React Native application receives a selected image using the react-native-image-picker library and I need to send that image to a back-end running a NestJS server. The endpoint uses #UseInterceptor and FileInterceptor to extract the image from the 'file' field of the formData received. However, when I fire the request to the endpoint, the file received is undefined.
Here is my React Native code sending the request with the file in the FormData as a payload.
const uploadNewProfileImage = async () => {
if (!newProfileImage?.assets) return;
const formData = new FormData();
const profileImage = newProfileImage.assets[0];
console.log(profileImage);
if (profileImage.uri && user) {
formData.append(
'file',
JSON.stringify({
uri:
Platform.OS === 'android'
? profileImage.uri
: profileImage.uri.replace('file://', ''),
name: profileImage.fileName,
type: profileImage.type
})
);
client // client is an Axios instance that injects Bearer Token
.post(`/user/profile/${user.uid}/image`, formData)
.then(({ data }) => {
console.log(data);
})
.catch((err) => {
console.log(err.response);
setShowImageUploadError(true);
})
.finally(() => {
getUserProfile();
});
}
};
Here is my back-end NestJS code extracting the file.
// User.controller.ts
#UseGuards(UserGuard)
#ApiBearerAuth()
#ApiUnauthorizedResponse({ description: 'Unauthorized' })
#UseInterceptors(FileInterceptor('file', { limits: { fileSize: 20000000 } }))
#Post('/profile/:uid/image')
#ApiOkResponse({ type: UploadProfileResponse })
#ApiBadRequestResponse({ description: 'Image too large OR Invalid image type' })
async uploadProfilePicture(#UploadedFile() file: Express.Multer.File, #Request() req): Promise<UploadProfileResponse> {
const uid = req.user.uid;
const imageUrl = await this.userService.uploadProfilePicture(uid, file);
return imageUrl;
}
}
I tried to set the axios request header in the axios config like so
{
headers: {
'Content-Type': 'multipart/form-data; boundary=——file'
}
}
I tried chaning the back-end endpoint to the following
#UseGuards(UserGuard)
#ApiBearerAuth()
#ApiUnauthorizedResponse({ description: 'Unauthorized' })
#UseInterceptors(FileFieldsInterceptor([{ name: 'file' }], { limits: { fileSize: 20000000 } }))
#Post('/profile/:uid/image')
#ApiOkResponse({ type: UploadProfileResponse })
#ApiBadRequestResponse({ description: 'Image too large OR Invalid image type' })
async uploadProfilePicture(#UploadedFiles() file: Array<Express.Multer.File>, #Request() req): Promise<UploadProfileResponse> {
const uid = req.user.uid;
console.log("File", file);
const imageUrl = await this.userService.uploadProfilePicture(uid, file[0]);
return imageUrl;
}
Nothing seems to be working, and the file extracted from the backend is still undefined.
Any help would be greatly appreciated.

Not able to upload file using NestJs and Multer

I am trying to upload files to aws s3 bucket using Nestjs
#Post('uploadfile/:bucketName')
#UseInterceptors(FileInterceptor('file'))
async addAvatar(#UploadedFile() file: Express.Multer.File, #Param('bucketName') bucketName: string): Promise<S3.ManagedUpload.SendData> {
return this.s3ManagerService.uploadFile(file.buffer, file.originalname, bucketName);
}
and my Postrequest is:
let formData = new FormData();
formData.append("file", fs.createReadStream(path.join(__dirname, `./uploads/${uploadedFileName}.jpg`)), file.data.originalname);
console.log(JSON.stringify(formData.getHeaders()));
const response = await axios.post("my_url", formData, {
...formData.getHeaders(),
});
Getting an error always :
[Nest] 5082 - 14/09/2021, 19:36:48 ERROR [ExceptionsHandler] Cannot read property 'buffer' of undefined
TypeError: Cannot read property 'buffer' of undefined
Could you please help me if I am missing something here.
It indicates that your file is not uploaded, Probably because it is expected to be send as multipart/formData. Try this instead:
const response = await axios.post("my_url", formData, {
headers: {
"content-type": "multipart/form-data"
},
});

Cloudinary\Error: Missing required parameter - file - Express and Postman

first time trying to upload images to Cloudinary and I have come across an issue when using Express via Postman.
Using form-data on setting 'file' to upload an image to Cloudinary
As of now, when I try to access the req.body I get an empty object, so I guess that has to do with why cloudinary.uploader.upload cannot read the file passed as its first param, since its req.body.file, as shown in the code below.
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_KEY,
api_secret: process.env.CLOUDINARY_SECRET
})
exports.upload = async (req, res) => {
try{
console.log(req.body);
const result = await cloudinary.uploader.upload(req.body.file, {
public_id: `${Date.now()}`,
resource_type: "auto"
})
return res.json({
public_id: result.public_id,
url: result.secure_url
})
}catch(err){
console.log(err)
}
}
The error message I get:
{
message: 'Missing required parameter - file',
name: 'Error',
http_code: 400
}
Any suggestions to solve this issue?
I solved it! I was not able to pass the form-data as req.body to the server, so I had to try and access it through req.files, but was not able to with that either, so I searched a bit and found a middleware 'express-fileupload', and that did the trick. I just added it in my app.js and used
const fileupload = require('express-fileupload');
app.use(fileupload({useTempFiles: true}))
So now I can access my req.files.
exports.upload = async (req, res) => {
const file = req.files.image
try{
console.log(file);
const result = await cloudinary.uploader.upload(file.tempFilePath, {
public_id: `${Date.now()}`,
resource_type: "auto"
})
res.json({
public_id: result.public_id,
url: result.secure_url
})
}catch(err){
console.log("Error", err)
return res.status(400).json({error: err})
}
}
The response I get is:
{
name: 'some-image.png',
data: <Buffer >,
size: 99770,
encoding: '7bit',
tempFilePath: ' **C:\\filepath\some-image.png** ',
truncated: false,
mimetype: 'image/png',
md5: 'b5f612a571442bf604952fd12c47c1bf',
mv: [Function: mv]
}
POST /cloudinary/upload-images 200 1617.944 ms - 119
And it is uploaded successfully to my Cloudinary.
const result = await cloudinary.uploader.upload(req.file, {
public_id: ${Date.now()},
resource_type: "auto"
})
and add file from form data and type should be File
Solved!
This is how i am setting the FormData
let myTestForm = new FormData();
myTestForm.set("name", name);
myTestForm.set("email", email);
myTestForm.set("Avatar", Avatar);
myTestForm.set("password", password);
This is how i am using the FormData
const config = {
headers: {
"Content-type": "multipart/form-data",
},
};
const { data } = await axios.post(`/api/v1/register`, userData, { config });
please don't pass it this way { userData} , had struggled for with this :/
This is how i am uploading image
const myCloud = await cloudinary.v2.uploader.upload(req.body.Avatar, {
folder: "Avatars",
width: 150,
crop: "scale",
public_id: `${Date.now()}`,
resource_type: "auto",
});
PS : in my case i had to upload only 1 image. Have not passed any parameter in app.js file
app.use(bodyParser.urlencoded({ extended: true }));
app.use(fileUpload());

Upload Image from triggerio to express.js fails

I'm trying to post a file from a mobile triggerio app to a nodejs service. The request hits the post method, but the fails because the form object is null in the request obj.
(TypeError: Cannot call method 'complete' of undefined)
I've adapted the code from the accepted answer in this post : Uploading images using Node.js, Express, and Mongoose
This is my current nodejs code:
var express = require('express')
, form = require('connect-form');
var app = express.createServer(
form({ keepExtensions: true })
);
app.post('/fileupload', function(req, res, next){
//req. form is nulL
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(process.env.PORT);
console.log("express started");
And this is my upload method in triggerio:
function uploadFile (file){
forge.request.ajax({
url: 'http://resttrigger.aykarsi.c9.io/fileupload',
type: 'POST',
files: [file],
fileUploadMethod: 'raw',
dataType: 'json',
success: function (data) {
forge.logging.log("success " + data);
},
error: function (e) {
forge.logging.log("error " + e);
}
});
}
Using fileUploadMethod: 'raw' might be the problem here: it means that the request body is just a binary blob, rather than the multipart-encoded form which your node code expects.
For reference, here is a minimal handler that will save uploaded files into /tmp:
exports.upload = function(req, res){
var filename = '/tmp/' + new Date().getTime();
console.log(JSON.stringify(req.files));
// replace "test" with your actual form field name
fs.readFile(req.files["test"].path, function (err, data) {
fs.writeFile(filename, data, function (err) {
res.send({filename: filename});
});
});
};