Foolproof Guide to Image Upload in Two Hours

“Your Majesty, I have recently been developing an image upload feature, but I feel it’s not elegant enough. Could you please give me some guidance?” The concubine hurriedly came to ask.

“Oh? Let me see the code you wrote.”

function uploadImage() {    const input = document.getElementById('fileInput');    const file = input.files[0];    const formData = new FormData();    formData.append('image', file);    fetch('/upload', {        method: 'POST',        body: formData    })    .then(response => response.json())    .then(data => console.log('Success:', data))    .catch(error => console.error('Error:', error));}

“Hmm, the code has the basic functionality, but it can indeed be more elegant. Let me help you refactor it with Cursor.”

“Cursor? What kind of magical tool is that?” the concubine asked curiously.

“This is a programming tool I discovered recently! You see, just by typing ‘/refactor’ in Cursor, it can help us optimize the code structure. Come, let me show you a magic trick!”

class ImageUploader {    constructor(endpoint = '/upload') {        this.endpoint = endpoint;        this.supportedTypes = ['image/jpeg', 'image/png', 'image/gif'];        this.maxSize = 5 * 1024 * 1024; // 5MB    }    async upload(file) {        try {            if (!this.validateFile(file)) {                throw new Error('Invalid file type or size');            }            const formData = new FormData();            formData.append('image', file);            const response = await fetch(this.endpoint, {                method: 'POST',                body: formData            });            if (!response.ok) {                throw new Error(`Upload failed: ${response.statusText}`);            }            return await response.json();        } catch (error) {            console.error('Upload error:', error);            throw error;        }    }    validateFile(file) {        return this.supportedTypes.includes(file.type) &&                file.size <= this.maxSize;    }}

“Wow! This is so magical! The code suddenly became so elegant!” the concubine exclaimed.

“That’s right, this is just the tip of the iceberg with Cursor. Now, let me teach you another little trick. Type ‘/test’, and Cursor can automatically generate test code for us!”

describe('ImageUploader', () => {    let uploader;    beforeEach(() => {        uploader = new ImageUploader();    });    test('validates file type correctly', () => {        const validFile = new File([''], 'test.jpg', { type: 'image/jpeg' });        const invalidFile = new File([''], 'test.txt', { type: 'text/plain' });        expect(uploader.validateFile(validFile)).toBeTruthy();        expect(uploader.validateFile(invalidFile)).toBeFalsy();    });});

“That’s amazing! Is this what they call unit testing?” the concubine’s eyes sparkled.

“Exactly! But remember, Cursor is just a tool; the key is still to understand the core logic of the code. Now, let me teach you a practical scenario.”

“For instance, if we want to add an upload progress indicator, we just need to type ‘/enhance’ in Cursor…”

class ImageUploader {    // ... previous code remains unchanged ...    async uploadWithProgress(file, onProgress) {        if (!this.validateFile(file)) {            throw new Error('Invalid file type or size');        }        const formData = new FormData();        formData.append('image', file);        const xhr = new XMLHttpRequest();        return new Promise((resolve, reject) => {            xhr.upload.onprogress = (event) => {                if (event.lengthComputable) {                    const percentComplete = (event.loaded / event.total) * 100;                    onProgress(percentComplete);                }            };            xhr.onload = () => {                if (xhr.status === 200) {                    resolve(JSON.parse(xhr.response));                } else {                    reject(new Error(`Upload failed: ${xhr.statusText}`));                }            };            xhr.onerror = () => reject(new Error('Network error'));            xhr.open('POST', this.endpoint);            xhr.send(formData);        });    }}

“This way we can see the upload progress!” the Emperor said with a smile.

“This is really practical! So… can I use Cursor to assist me in coding from now on?” the concubine asked eagerly.

“Of course! But remember, Cursor is an auxiliary tool, and you shouldn’t rely on it completely. The key is still to understand the essence of the code. Alright, today’s lesson ends here; you should digest this first.”

“Thank you, Your Majesty! I will go practice right away!” the concubine said happily.

Tip:

  1. Cursor can be downloaded and installed from the official website.
  2. Common shortcut commands: ‘/refactor’, ‘/test’, ‘/enhance’.
  3. Remember to frequently check for Cursor updates to get the latest features.
  4. Make good use of Cursor’s code completion feature, but do not over-rely on it.

Remember, no matter how powerful the tool is, we still need to understand the core logic of the code. Go give it a try!

Like
Share
Just

Leave a Comment