首页 > 解决方案 > How to upload a file from Vue frontend to FastAPI backend

问题描述

Vuejs Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>


    <div id="file-upload-list" class="container">
        <div class="large-12 medium-12 small-12 cell">
          <label>File
            <input type="file" id="file" ref="file" v-on:change="handleFileUpload()"/>
          </label>
            <button v-on:click="submitFile()">Submit</button>
        </div>
    </div>
    
    

    <script>
        var fileList = new Vue({

            data(){
                return {
                    file: ''
                }
            },
            el: "#file-upload-list",
            methods: {
            /*
                Submits the file to the server
            */
            submitFile(){
                /*
                        Initialize the form data
                    */
                    let formData = new FormData();

                    /*
                        Add the form data we need to submit
                    */
                    formData.append('file', this.file);
                    console.log(this.file);
                    var baseURL="http://127.0.0.1:8000"

                /*
                Make the request to the POST /single-file URL
                */
                    axios.post( baseURL+'/uploadfiles',
                        // formData,
                        {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                        file:this.file
                       
                    }
                    ).then(function(){
                console.log('SUCCESS!!');
                })
                .catch(function(){
                console.log('FAILURE!!');
                });

                console.log(formData);
            },

            /*
                Handles a change on the file upload
            */
            handleFileUpload(){
                this.file = this.$refs.file.files[0];
            }
            }
            
        });
    </script>

</body>
</html>

FastAPI code


@app.post("/uploadfiles/")
async def create_upload_files(files: List[UploadFile] = File(...)):
    result=""
    for file in files:
        fpath = os.path.join(
            STORAGE_PATH, f'{file.filename}'
        )
        async with aiofiles.open(fpath, 'wb') as f:
            content = await file.read()
            await f.write(content)

        

    return {"message": "success"}

I am trying to upload a pdf file from vuejs to fastAPI. where pdf file will be saved in a particular location in fastAPI code mentioned. I have tested the fastapi code in postman and it works good and I also enabled cross-origin. I am new to vuejs and I don't know how to do form action functionality. Mainly I need to know HTTPFile transaction is happening in the vuejs

Error- Output

标签: javascriptpythonvue.jshttpfastapi

解决方案


推荐阅读