Hello everyone, I'm working on a web-to-print application and I'm using payload as the backend, I've already linked my media collection to my S3 Bucket, and modified my orders collection to have all the necessary fields and when I create an order through the admin panel it works fine,
and now I'd like to handle file (image) upload from the frontend, how do I go about doing that?Can anyone please tell me, or provide a link to a simmilar problem that anyone had? I'm wondering if there is
"a correct way"to do this.
Submit the form data to payload through the rest api. Or the local api, or graphql, up to you
Well every time I tried to use REST api I get errors saying I made a bad request and that images cannot be transfered
Maybe you have to first upload your image to the media collection then link it to the collection that you wanna upload to ? Im not sure its just a thought
I dont think so, because if I upload to my orders collections that is relatedTo media it should automatically process the media collection? I think... but I'm just having trouble getting any of the form data to the backend, it just does not want to work.
I'm having troubles creating endpoints and for all compleatly lost in the fetching and sending data
I allways get the error: "bad request 400"
const processForm = async (data: Inputs) => {
try {
// Step 1: Upload images
const uploadedImages = await Promise.all(
imageSettings.map(async (img) => {
const formData = new FormData();
formData.append('file', img.file);
const uploadResponse = await fetch('http://localhost:3000/api/media', {
method: 'POST',
body: formData,
});
if (!uploadResponse.ok) {
throw new Error(`Failed to upload image: ${img.file.name}`);
}
const uploadResult = await uploadResponse.json();
return {
image: uploadResult.id, // Use the returned image ID
printSize: img.size,
printType: img.printType
};
})
);
// Step 2: Create order with uploaded image IDs
const orderData = {
customerFirstName: data.firstName,
customerLastName: data.lastName,
customerEmail: data.email,
images: uploadedImages,
total: calculateTotal(imageSettings) // Assuming you have this function
};
const orderResponse = await fetch('http://localhost:3000/api/orders', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(orderData),
});
if (!orderResponse.ok) {
const errorText = await orderResponse.text();
throw new Error(`Server responded with ${orderResponse.status}: ${errorText}`);
}
const result = await orderResponse.json();
console.log('Order submitted successfully:', result);
// Handle successful submission (e.g., show success message, redirect)
} catch (error) {
console.error('Error submitting order:', error);
// Handle error (e.g., show error message to user)
}
};What am I doing wrong?
According to this it should be correct
are you able to make other successful requests with the rest api? could be something misconfigured with your image upload step. fwiw here's how i do it with the local API:
const imageReq = await fetch(imagePath)
// https://stackoverflow.com/a/17949292/2522025
const [contentType] = imageReq.headers.get('Content-Type').split(';')
// payload.logger.info(`contentType ${contentType}`)
const buffer = await imageReq.arrayBuffer()
const imageData = Buffer.from(buffer)
const res = await payload.create({
collection: 'media',
file: {
data: imageData,
mimetype: contentType,
name: filename,
size: imageData.length,
},
data: {
wordpress_id: wpId,
},
})Thanks, I'll get back to this tommorow, for now thanks for help, I'd like to keep this open so that I could maybe ask some follow-up questions
Hi, in your step 1, it appears you're returning an array of objects (image, printSize and printType), then trying to use that array in
orderData.images. Note that relationship fields accept only IDs of the related data, hence why you're getting validation error for
images.
Star
Discord
online
Get dedicated engineering support directly from the Payload team.