前端excel文件上传、后端处理

前端传统文件上传代码
使用element-ui中的upload组件
后端代码

前端传统文件上传代码
    # 使用input标签中 file属性,@change当输入框的值发生变化就会执行对应的方法
    <input type="file" @change="handleFileUpload" />

     # methods方法:
     handleFileUpload(event) {
                let file = event.target.files[0];
                // 获取到的是一个文件对象
                console.log(file) 
                
                // FormData 创建一个表单对象
                const formData = new FormData();
                // 添加值操作 key为files ,valuew为 file ; 后端提取的值就是这里的key值
                formData.append('files', file);
    
                axios({
                    url: "url地址",
                    method: "post",
                    data: formData,
                    headers: {
                        'Content-Type': 'multipart/form-data'   // 需要加请求头
                    }
                }).then((res) => {
                    console.log('上传成功', res.data)
                }).catch((error) => {
                    console.error('上传失败', error)
                })
使用element-ui中的upload组件
    <el-upload ref="upload" class="upload-demo" action="" :limit="1" :on-exceed="handleExceed"
            :auto-upload="false" :on-change="handleSuccess">
            <template #trigger>
                <el-button type="primary">上传数据</el-button>
            </template>
            <template #tip>
                <div class="el-upload__tip text-red">
                    请上传 .xlsx格式的文件
                </div>
            </template>
    </el-upload>
    <el-button type="primary" @click="submitData">提交</el-button>
    
    # data值
    upload :"",
    
    # methods
    // 文件上传成功
    handleSuccess(file, fileList) {
        this.upload = file.raw
      },

    // 提交数据
    submitData() {
        let formData = new FormData()
        formData.append('files', this.upload)
        console.log(formData.get("files"))

        axios({
            url: "url地址",
            method: "post",
            data: formData,
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then((res) => {
            console.log('上传成功', res.data)
        }).catch((error) => {
            console.error('上传失败', error)
        })
    },
后端代码
    @app.route("/api/addData", methods=['post'])
    def add_data():
        """新增数据"""
    
        try:
            # 方法一: 如果传的excel文件
            # 通过对应的key去获取excel文件
            files = request.files["files"]
            # 获取excel文件名称
            filename = files.filename
            
            # 方法二: 传的是文件存储的地址 (url)
            from io import BytesIO
            file_url = request.form("file_url")
            response = requests.get(file_url)
            content = response.content
            files = BytesIO(content)

            # 接下来的步骤都是一样,直接操作excel数据
            wb = openpyxl.load_workbook(files)
            sheet_names = wb.get_sheet_names()
            ws = wb.get_sheet_by_name(sheet_names[0])
            print("有多少行数据:%s" % ws.max_row)
            print("有多少列数据:%s" % ws.max_column)
    
            # 保存excel,尽量写完整的路径,写相对的路径可能保存失败
            filename = get_time() + "_" + files.filename
            cache = get_project_path() + "\\cache\\qualityScore\\%s" % filename
            files.save(cache)
            print(cache)
            return ""

        except Exception as e:
            return {"result": "error", "info": e}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。

文章标题:前端excel文件上传、后端处理

本文作者:伟生

发布时间:2023-06-10, 10:01:01

最后更新:2023-06-10, 12:09:47

原始链接:http://yoursite.com/2023/06/10/qianduan_05_upload/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录
×

喜欢就点赞,疼爱就打赏