Form Data Append Method Not Working In Angular 8 - javascript

I've been struggling with this problem for sometime now and its very frustrating. I've been trying to use Javascript's FormData to upload a file and it seem the file doesn't get sent to the server.
uploadCoverImages() {
const form = new FormData();
const files = this.coverImagesFiles; // const files is now a Files[] object
for (let i = 0; i < files.length; i++) {
const imageFile = files[i];
console.log(imageFile); // return the right file data
form.append('image', imageFile, imageFile.name);
this.http.post(this.uploadUrl, form, { headers: this.headers }).subscribe(
res => {
console.log('res : ' + res);
},
err => {
console.log('err: ' + err); // always get an error saying file is empty
}
);
}
}
This is my http header code:
getFileUploadHeader() {
const token = sessionStorage.getItem('token');
const headers = new HttpHeaders({ // Angular's HttpHeader
'Content-Type': 'multipart/form-data',
'Accept': 'application/json', // some google searches suggested i drop this but it still doesnt work
'Authorization': 'Bearer ' + token
});
return headers;
}
My PHP code (Laravel 5) is expecting a file with key like this:
public function imageUpload(Request $request)
{
if($request->hasFile('image'))
{
return Reponse::json('file ok');
}
else
{
return Response::json('no file');
}
}
I just dont know why form data doesnt send the file or if am doing something wrong at the server side. How do i get this work. Please help!!!

Related

How to read files after sending a post request in the req.body

I am running into an issue where when I want to upload an image to s3 bucket nothing goes through.
Basically the only message I get is
API resolved without sending a response for /api/upload/uploadPhoto, this may result in stalled requests.
In the front end, I have an input which can take multiple files ( mainly images ) and then those are stored in event.target.files.
I have a function that stores each file in a state array, and with the button submit it sends a post request to my next.js API.
Here's the logic on the front end:
This function handles the photos, so whenever I add a photo it will automatically add it to the listingPhotos state:
const handleListingPhotos = async (e: any) => {
setMessage(null);
let file = e.target.files;
console.log("hello", file);
for (let i = 0; i < file.length; i++) {
const fileType = file[i]["type"];
const validImageTypes = ["image/jpeg", "image/png"];
if (validImageTypes.includes(fileType)) {
setListingPhotos((prev: any) => {
return [...prev, file[i]];
});
} else {
setMessage("Only images are accepted");
}
}
};
Once the photos are stored in the state, I am able to see the data of the files in the browsers console.log. I run the onSubmit to call the POST API:
const handleSubmit = async (e: any) => {
e.preventDefault();
const formData = new FormData();
formData.append("files[]", listingPhotos);
await fetch(`/api/upload/uploadPhoto`, {
method: "POST",
headers: { "Content-Type": "multipart/form-data" },
body: formData,
}).then((res) => res.json());
};
console.log("listingphotos:", listingPhotos);
Which then uses this logic to upload to the S3 Bucket, but the issue is that when I log req.body I am getting this type of information:
req.body ------WebKitFormBoundarydsKofVokaJRIbco1
Content-Disposition: form-data; name="files[]"
[object File][object File][object File][object File]
------WebKitFormBoundarydsKofVokaJRIbco1--
api/upload/UploadPhoto logic:
import { NextApiRequest, NextApiResponse } from "next";
const AWS = require("aws-sdk");
const access = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
};
// creates an S3 Client
const s3 = new AWS.S3({ region: "region", credentials: access });
export default async function uploadPhoto(
req: NextApiRequest,
res: NextApiResponse
) {
// take info from parent page
// console.log("req.body: ", req.body);
if (req.method === "POST") {
console.log("req.body", req.body);
let body = req.body;
let headers = req.headers;
let contentType = headers["Content-Type"] || headers["content-type"];
// check for correct content-type
if (!contentType.startsWith("multipart/form-data")) {
return { statusCode: 400, body: "Invalid content type" };
}
let boundary = contentType.replace("multipart/form-data; boundary=", "");
let parts = body.split(boundary);
for (let part of parts) {
if (part.startsWith("Content-Disposition")) {
let [fileData] = part.split("\r\n\r\n");
fileData = fileData.slice(0, -2);
let [fileName] = part.split("filename=");
fileName = fileName.slice(1, -1);
let params = {
Bucket: "RANDOM BUCKET NAME",
Key: fileName,
Body: fileData,
ContentType: { "image/png": "image/jpg" },
};
// Need to set the PARAMS for the upload
await s3.putObject(params);
console.log(
"Successfully uploaded object: " + params.Bucket + "/" + params.Key
);
}
}
return {
statusCode: 200,
body: "File uploaded",
};
// Uploads the files to S3
}
}
I was able to find a way to read if the files were correctly displayed.
req.body {
fileName: 'b699417375e46286e5a30fc252b9b5eb.png',
fileType: 'image/png'
}
POST request code was changed to the followng:
const s3Promises = Array.from(listingPhotos).map(async (file) => {
const signedUrlRes = await fetch(`/api/upload/uploadPhoto`, {
method: "POST",
body: JSON.stringify({
fileName: file.name,
fileType: file.type,
}),
headers: { "Content-Type": "application/json" },
});
Obviously, this is not the solution but it's part of it. The only problem I am running into right now is handling CORS in order to see if the files are sent to the bucket.

how to fix uri undefined error when trying to send request

when I'm trying to call the request in front node, I'm getting error in my backend node " RequestError: Error: Invalid URI "undefined"" , it seems like backend node request is not getting the data form my frontend node request.
knowing that uploadLink already have a value and in my browser console the frontend request looks ok
my backend request code
const ThumbnailUpload = async (req, res) => {
const { Uploadlink } = req.body;
const { selectedFile } = req.body;
const clientServerOptions = {
uri: `${Uploadlink}`,
body: JSON.stringify({
name: selectedFile,
}),
method: 'PUT',
headers: {
'Content-Type': ' application/json',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
Authorization: getVimeoAuthorization(),
},
};
request(clientServerOptions, function (error, response) {
if (error) {
res.send(error);
} else {
const body = JSON.parse(response.body);
res.send(body);
}
console.log(Uploadlink);
});
};
and my frontend code is
const handleSubmit = (event) => {
event.preventDefault();
const formData = new FormData();
formData.append(
'selectedFile',
new Blob([selectedFile], { type: 'image/jpg, image/png, or image/gif' }),
);
formData.append('uploadLink', uploadLink);
const headers = {
'Content-Type': 'image/jpg, image/png, or image/gif',
Accept: 'application/vnd.vimeo.*+json;version=3.4',
};
try {
axios
.post(`${backendPostPath}/thumbnail-upload`, formData, {
headers,
})
.then((response) => {
applyThumbnial();
console.log(response);
});
} catch (error) {
console.log(error);
}
};
any advise ?
change:
const { Uploadlink } = req.body;
to:
const { uploadlink } = req.body;
make variable consistent throughout the code
EDIT
also, since you're uploading a file, you need to use upload middleware before request handler, and file will be within req.file:
route.post('/thumbnail-upload', upload.single('selectedFile'), ThumbnailUpload);
//... handler..
const selectedFile = req.file;

React axios multiple files upload

I'm trying upload multiple images with axios in React but i cannot figure out what is wrong. First I tried to upload single image and that work just fine. But with multiple images I'm out of options.
I'm creating FormData like so:
for (let i = 0; i < images.length; i++) {
formData.append('productPhotos[' + i + ']', images[i]);
}
The axios request looking like this
const config = { headers: { 'Content-Type': 'multipart/form-data' } };
axios
.post(endPoints.createProduct, formData, config)
.then(res => console.log(res))
.catch(err => console.log(err));
My back-end is written is node/express and I'm using multer for uploading. The signature is look like this:
app.post("/product", upload.array("productPhotos"), (req, res) => {
I tried this back-end end point in PostMan and uploading works for just fine, so the error must be on front-end. Thanks for help.
UPDATE
Right way to pass multiple files in formData:
images.forEach(img => {
formData.append("productPhotos", img)
})
Here is a full working set up (expanded version of the answer above)
Client side:
// silly note but make sure you're constructing files for these (if you're recording audio or video yourself)
// if you send it something other than file it will fail silently with this set-up
let arrayOfYourFiles=[image, audio, video]
// create formData object
const formData = new FormData();
arrayOfYourFiles.forEach(file=>{
formData.append("arrayOfFilesName", file);
});
axios({
method: "POST",
url: serverUrl + "/multiplefiles",
data: formData,
headers: {
"Content-Type": "multipart/form-data"
}
})
//some error handling
Server side (express, node - mutler)
const UPLOAD_FILES_DIR = "./uploads";
const storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, UPLOAD_FILES_DIR);
},
// in case you want to change the names of your files)
filename(req, file = {}, cb) {
file.mimetype = "audio/webm";
// console.log(req)
const {originalname} = file;
const fileExtension = (originalname.match(/\.+[\S]+$/) || [])[0];
cb(null, `${file.fieldname}${Date.now()}${fileExtension}`);
}
});
const upload = multer({storage});
// post route that will be hit by your client (the name of the array has to match)
app.post("/multiplefiles", upload.array('arrayOfFilesName', 5), function (req, res) {
console.log(req.files, 'files')
//logs 3 files that have been sent from the client
}
This is not the right way to generate keys. You can try something like this:
let productimages = [];
for (let i = 0; i < images.length; i++) {
productimages.push(images[i]);
}
formData.append('productPhotos', productimages);
You may want to send the files as an array to the endpoint:
images.forEach( img => {
formData.append('productPhotos[]', img);
})

Sending multiple files to Laravel backed using Vue.js

I'm using a multi-step form in Vue.js to send multiple files to a Laravel backend. The form gives the user the ability to add multiple users to the database. Each user requires a file to be uploaded along with it.
Files are initially stored in state using Vuex. Each file is pushed to a files array in store.js
When the user submits the form, the files array looks as follows:
When the user submits the form I'm adding all the individual form data including the files array to a new FormData() object like so:
let fd = new FormData();
// append each file
for( var i = 0; i < store.state.files.length; i++ ){
let file = store.state.files[i];
fd.append('files[' + i + ']', file);
console.log(file);
}
// append rest of form data
fd.append('appointments', store.state.appointments);
fd.append('business_details', store.state.business_details);
fd.append('business_names', store.state.business_names);
fd.append('directors', store.state.directors);
fd.append('share_amount', store.state.share_amount);
fd.append('shareholders', store.state.shareholders);
Once all the form data is added I use Axios to send the form data to my Laravel backend.
axios.post('/businesses', fd, {
headers: {
'content-type': 'multipart/form-data'
}
})
.then(response => {
console.log(response);
this.completeButton = 'Completed';
})
.catch(error => {
console.log(error)
this.completeButton = 'Failed';
})
Inside my Laravel BusinessController I then want to Log::debug($_FILES) to see what files were sent along but all I get is an empty array.
[2018-10-05 16:18:55] local.DEBUG: array (
)
I've checked that the headers I'm sending includes 'multipart/form-data' and that I'm appending all my form data to new FormData() but I cannot figure out why the server receives an empty $_FILES array.
UPDATE 1:
If I Log::debug($request->all()); I get:
If I try to store the objects in that file like so:
foreach ($request->input('files') as $file) {
$filename = $file->store('files');
}
I get the following error:
[2018-10-06 09:20:40] local.ERROR: Call to a member function store() on string
Try this case:
var objectToFormData = function (obj, form, namespace) {
var fd = form || new FormData();
var formKey;
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (namespace) {
formKey = namespace + '[' + property + ']';
} else {
formKey = property;
}
// if the property is an object, but not a File,
// use recursivity.
if (typeof obj[property] === 'object' && !(obj[property] instanceof File)) {
objectToFormData(obj[property], fd, property);
} else {
// if it's a string or a File object
fd.append(formKey, obj[property]);
}
}
}
return fd;
};
Reference : objectToFormData
Axios :
axios.post('/businesses', fd, {
transformRequest: [
function (data, headers) {
return objectToFormData(data);
}
]
})
.then(response => {
console.log(response);
this.completeButton = 'Completed';
})
.catch(error => {
console.log(error)
this.completeButton = 'Failed';
})
Try changing this line:
fd.append('files[' + i + ']', file);
To this:
fd.append('files[]', file);

Upload image to Slack with axios

I'm trying to upload an image to slack using the slack api https://api.slack.com/methods/files.upload.
function uploadImage(file) {
var form = new FormData();
form.append('image', file);
var self = this;
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
var token = 'myToken'
axios.post('https://slack.com/api/files.upload?token=' + token, form, config)
.then(function (response) {
console.log(response);
self.imageUploaded("Image uploaded")
})
.catch(function (error) {
console.log(error);
self.error(error);
})
}
I'm getting response with "invalid form data". Any idea what might be going wrong?
Thanks and best regards!
PS: I was able to post an image to slack with python
def post_image(filename, token, channels):
f = {'file': (filename, open(filename, 'rb'))}
response = requests.post(url='https://slack.com/api/files.upload',
data={'token': token, 'channels': channels},
headers={'Accept': 'application/json'},
files=f)
return response.tex
Just need to make the same request with axioms
you can upload a file using axios with the form-data lib
const fs = require("fs");
const axios = require("axios");
const FormData = require("form-data");
const form = new FormData();
form.append("token", 'token here');
form.append("channels", channelId);
form.append("file", fs.createReadStream(__dirname + "/aapl.png"), 'file name');
try {
const res = await axios.post("https://slack.com/api/files.upload", form, {
headers: form.getHeaders(),
});
} catch (err) {
throw new Error(err);
}

Categories