Upload an Image to wix using POST method in a http-request

Hi, I have been using http request in wix to fetch data, delete data and all that. But yeasterday I decided to learn POST method. So far it’s been working great but then it hit me, what if I want to upload files, how would that be possible?

I promise I’ve read through the upload() function, it seems to make sense but it’s not working

The request is simple, the http-body has an image decoded to a base64 string. Something like this:
/9j/4AAQSkZJRgABAQAA2ADYAAD/4QCARXhpZgAATU0AKgAAAAgABQESAAMAAAABAAEAAAEaAAUAAAABAAAASgEbAAUA…

Here’s my code:
(I have the buffer npm module installed)

import { Buffer } from 'buffer'

export function post_upload(request) {
    let type;
    let body
    if (request.query) {
        type = request.query.type
        body = request.body
    }
    let options = {
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
        }
    }
    var buffer = Buffer.from(unescape(body), 'base64');
    if (buffer) {
        return uploadImage(buffer)
            .then(image => {
                options.body = [{
                    "message": "success"
                }]
                console.log(options)
                return ok(options)
            })
            .catch((err) => {
                options.body = [{
                    "message": "error"
                }]
                console.log(options)
                return serverError(options)
            })
    } else {
        options.body = [{
            "noData": "error"
        }]
                console.log(options)
        return serverError(options)
    }
}
export function uploadImage(buffer) {
    return mediaManager.upload(
    "/uploads/subfolder", 
    buffer, 
    "img_1797.jpg", {
        "mediaOptions": {
            "mimeType": "image/jpeg",
            "mediaType": "image"
        },
        "metadataOptions": {
            "isPrivate": false,
            "isVisitorUpload": true,
            "context": {
                "someKey1": "someValue1",
                "someKey2": "someValue2"
            }
        }
    });
}

The request is sending sucessfully, I’m not getting any server errors (Sometimes I get status code 500 other than that nothing just happens). No Image is uploaded because I don’t see anything in the visitor uploads folder.

NOTE: I’m sending the request through Swiftui/Xcode

Please point out where I’m wrong,
Brendan Okey-iwobi

Here’s something I wrote a long time ago (I guess I’d write it better today, but you can use it to figure out the basic principles)

export function post_upload(request) {
let options = {
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
        }
    }
return req.body.json()
.then(body => {
return uploadImage(body);
})
.then(() => {
return ok(options);
})
.catch(err => {
options.body = { "err": err };
return serverError(options);
})
}
export async function uploadImage(data) {
	const exsitingUrl = await  searchForImage(data.hash)//the hash is a short file identifier that I send with the request payload to avoid uploading the same file twice. You can ignore it.
	if(exsitingUrl){return exsitingUrl;}
	let buffer = data.image;//this is the base64
	let userId = data.userId;
	let id = data.hash;
	let fileType;
	fileType = buffer.split("/")[1].split(";")[0];
	let fileName = data.fileName;
	if(!fileName){fileName = `newfile.${fileType}`;}
	buffer = buffer.split(`data:image/${fileType};base64,`)[1];
	if(fileType === "jfif"){fileType = "jpg";}
	buffer = Buffer.from(buffer, "base64")
	return mediaManager.upload(
			`/usersImages/${userId}`,
			buffer,
			fileName, {
				mediaOptions: {
					mimeType: `image/${fileType}`,
					mediaType: "image"
				},
				metadataOptions: {
					isPrivate: false,
					isVisitorUpload: true,
					context: {
						isUserFile: true,
						id: id
					}
				}
			}
		)
.then(image => {
if(image){
if(image.fileUrl){
let url = image.fileUrl;
if(typeof url !== "string"){return undefined;}				
wixData.save("UserImages", {_id: data.hash, image: url, originalName: fileName});				
return url;
	}
}
return;
})
catch(err => {
console.log("<<<<<<failed to upload image>>>>>>>>", err);
return Promise.reject(err);
});
}

function searchForImage(hash){
	return wixData.get("UserImages", hash)
	.then(r => {
		if(r){
			if(r.image){
				return r.image;//this is the URL
			}
		}
		return undefined;
	}).catch(r => undefined);
}

Hey,

Thank you so much! I had to make a lot of tweaks to get it working for me. I really appreciate this

Brendan Okey-iwobi

@okeyiwobi can you shared the tweaked code please?

Here’s mine that works for me:


export function post_upload(request) {
    let options = {
        "headers": {
            "Content-Type": "application/json",
            "Access-Control-Allow-Origin": "*",
        }
    }
    return request.body.json()
        .then(body => {
            if (body.secPassword == "vHiTpNq4934q4jecgU2a") {
                return uploadImage2(body.uploadImageData)
            } else {
                options.body = { "err": "Wrong Auth Password" };
                return serverError(options);
            }
        })
        .then((resp) => {
            options.body = { "url": "https://static.wixstatic.com/media/" + resp.split("/")[3] }
            return ok(options)
        })
        .catch(err => {
            options.body = { "err": err };
            return serverError(options);
        })
}

Here’s the main upload process:


export async function uploadImage2(data) { // notusing
    let buffer = data.dataURI; //this is the base64
    let userId = data.userId;
    let fileType
    let id = `${data.artistName}${data.userId}${generatePassword(10)}`
    let fileName = data.fileName;
    if (!fileName) { fileName = `${data.userId}`; }
    buffer = Buffer.from(buffer, "base64")
    return mediaManager.upload(
            `/usersImages/${userId}`,
            buffer,
            fileName, {
                "mediaOptions": {
                    "mimeType": `image/jpeg`,
                    "mediaType": "image"
                },
                "metadataOptions": {
                    "isPrivate": false,
                    "isVisitorUpload": true,
                    "context": {
                        "isUserFile": true,
                        "id": id
                    }
                }
            }
        )
        .then(image => {
            if (image) {
                if (image.fileUrl) {
                    let url = image.fileUrl;
                    if (typeof url !== "string") { return undefined; }
                    return url;
                }
            }
            return;
        })
        .catch(err => {
            console.log("<<<<<<failed to upload image>>>>>>>>", err);
            // return Promise.reject(err);
            return err;
        });
}

You don’t have add the artist name, userid etc…

– Brendan Okey-Iwobi