Skip to content

Latest commit

 

History

History
126 lines (122 loc) · 4.92 KB

05-upload.md

File metadata and controls

126 lines (122 loc) · 4.92 KB

File Upload in React

  • FormData is a built-in object in the browser that allows us to create key-value pairs of data, which can then be sent to the server in a POST request.
  • Uses the same format as a form with enctype="multipart/form-data"

Lab assignment 1

  1. Continue last exercise. Create a new branch 'upload' with git.
  2. Add VITE_UPLOAD_SERVER=https://10.120.32.94/upload/api/v1 to .env.local file. This is the file server where we will upload the files.
  3. Create Upload.jsx to views
  4. Add upload to routing in App.jsx
    • Add Upload to imports
    • Add <Route path="/upload" element={<Upload/>}/> to Routes
    • Add <Link to="/upload">Upload</Link> to Nav in Layout.jsx
  5. Add <form> to Upload.jsx with file input and submit button:
    // Upload.jsx
    const Upload = () => {
        const [file, setFile] = useState(null);
        return (
            <>
                <h1>Upload</h1>
                <form onSubmit={handleSubmit}>
                    <div>
                        <label htmlFor="title">Title</label>
                        <input
                            name="title"
                            type="text"
                            id="title"
                            onChange={handleInputChange}
                        />
                    </div>
                    <div>
                        <label htmlFor="description">Description</label>
                        <textarea
                            name="description"
                            rows={5}
                            id="description"
                            onChange={handleInputChange}
                        ></textarea>
                    </div>
                    <div>
                        <label htmlFor="file">File</label>
                        <input
                            name="file"
                            type="file"
                            id="file"
                            accept="image/*, video/*"
                        onChange={handleFileChange}
                        />
                    </div>
                    <img
                        src={
                            file
                            ? URL.createObjectURL(file)
                            : 'https://via.placeholder.com/200?text=Choose+image'
                        }
                        alt="preview"
                        width="200"
                    />
                    <button
                        type="submit"
                        disabled={file && inputs.title.length > 3 ? false : true}
                    >
                        Upload
                    </button>
                </form>
            </>
        );
    };
  6. We can use useForm hook to handle title and description but for file input we need to create a new function handleFileChange:
    // Upload.jsx
    const handleFileChange = (evt) => {
        if (evt.target.files) {
            console.log(evt.target.files[0]);
            // TODO: set the file to state
        }
    };
  7. Submitting the form:
    // Upload.jsx
    const doUpload = async () => {
        try {
            // TODO: call postFile function (see below)
            // TODO: call postMedia function (see below)
            // TODO: redirect to Home
        } catch (e) {
            console.log(e.message);
        }
    };
    • To upload the file to the file server, create a new hook useFile to ApiHooks.js. Then add a new function postFileto useFile hook:
    // ApiHooks.js
    const postFile = async (file, token) => {
        // TODO: create FormData object
        // TODO: add file to FormData
        // TODO: upload the file to file server and get the file data (url = import.meta.env.VITE_UPLOAD_SERVER + '/upload')
        // TODO: return the file data.
    };
    • Then add new function postMedia to useMedia hook:
    // ApiHooks.js
    const postMedia = async (file, inputs, token) => {
        // TODO: create a suitable object for Media API: without media_id, user_id, thumbnail and created_at. All those are generated by the API. See the media API documentation.
        // TODO: post the data to Media API and get the data as MediaResponse
        // TODO: return the data
    };
    • Finally, add postFile and postMedia function calls to doUpload function.
    • Test the app. Upload a file and check that it is added to the media list.

Submit

  1. Run npm build or npm run build
  2. Move build folder to your public_html
  3. Test your app: http://users.metropolia.fi/~username/upload
  4. Modify README.md. Change the link in Open [X](X) to view it in the browser. to point to the above link.
  5. git add, commit & push to remote repository
  6. Submit the link to correct branch of your repository to Oma