vue2项目上传图片

1.

2.

  <el-upload
              style="display: flex; flex-direction: row"
              class="avatar-uploader"
              name="upfile"
               action="#"
              :accept="accept"
               :show-file-list="false"
                ref="upload"
                auto-upload
                :on-success="uploadSuccess"
                :http-request="(params) => 
                httpUploadFile(params, index)" >
           <div>
             <img v-if="logoImage" :src="logoImage" class="avatar" />
             <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </div>
</el-upload>

3.上传对象的方法

 定义数据:
  data(){
     return:{
              logoImage: '',
              accept: '.jpg,.jpeg,.png,.JPG,.JPEG',
             }
        },
//上传图片
        httpUploadFile(param, index) {
            console.log('进入uploadFile');
            let that = this;
            let url = api.fileUploadUrl;
            const imgObj = new Image();
            imgObj.src = URL.createObjectURL(param.file);
            imgObj.setAttribute('crossOrigin', 'Anonymous');
            let fileId = '';
            if (that.value && that.value != '') {
                fileId = that.value;
            } else {
                //没有fileid的前端生成
                fileId = that.setNewValue();
            }
            var formData = new FormData();
            formData.append('file', param.file);
            formData.append('fileid', fileId);
            formData.append('__sid', localStorage.getItem('sessionId'));
            formData.append('height', imgObj.height || 110);
            formData.append('width', imgObj.width || 110);
            let size = parseFloat(param.file.size / 1024 / 1024);
            if (size > 10) {
                that.$message.warning('文件过大,无法上传');
                return;
            }
            uploadFile(url, formData)
                .then((res) => {
                    console.log('附件上传返回', res);
                    let body = res.body;
                    that.value = body.fileId;
                    body.name = body.fileOldName;

                    body.url = api.severUrl + body.imgUrl;
                    body.path = api.severUrl + body.imgUrl;

                    body.uid = param.file.uid;
                    // that.paramObj.fileId = body.fileId;
                    // that.fileLists.push(body);
                    this.logoImage = body.url;
                    // console.log(this.$refs.upload[index])

                    // this.$refs.upload[index].clearFiles();
                })
                .catch((err) => {
                    //异常报错
                    console.log(err);
                    that.$message.warning('上传失败,请稍后再试');
                });
        },

3.

   setNewValue() {
            var date = new Date();
            var timeStr = date.getFullYear() + '';
            timeStr = timeStr.substring(2);
            if (date.getMonth() < 9) {
                // 月份从0开始的
                timeStr += '0';
            }
            timeStr += date.getMonth() + 1;
            timeStr += date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
            timeStr += '';
            timeStr += date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
            timeStr += '';
            timeStr += date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
            timeStr += '';
            timeStr += date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
            let cur = '';
            for (let i = 0; i <= 5; i++) {
                cur += '' + Math.floor(Math.random() * 10);
            }
            timeStr = timeStr + cur;
            return timeStr;
        },

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Vue2 前端上传图片到后端,一般可以使用以下步骤: 1. 创建一个表单,包含一个类型为 `file` 的输入框,用于选择要上传的图片文件。 2. 在 Vue 组件中,监听文件选择事件,获取选中的文件。 3. 使用 `FormData` 对象创建一个表单数据对象,将选中的文件添加进去。 4. 发送 `POST` 请求到后端,携带表单数据对象作为请求体。 5. 在后端中,使用框架提供的文件上传功能,将文件保存到服务器指定的目录中。 以下是一个简单的示例代码: 前端部分(Vue 组件): ```html <template> <div> <form @submit.prevent="upload"> <input type="file" ref="fileInput" @change="handleFileSelect"> <button type="submit">上传</button> </form> </div> </template> <script> export default { data() { return { selectedFile: null }; }, methods: { handleFileSelect(event) { this.selectedFile = event.target.files[0]; }, upload() { const formData = new FormData(); formData.append("image", this.selectedFile); axios.post("/api/upload", formData).then(response => { // 处理上传成功后的响应 }); } } }; </script> ``` 后端部分(使用 Express 框架): ```javascript const express = require("express"); const multer = require("multer"); const app = express(); const upload = multer({ dest: "uploads/" }); app.post("/api/upload", upload.single("image"), (req, res) => { // req.file 包含上传的文件信息 res.send("上传成功!"); }); app.listen(3000, () => { console.log("服务器启动成功!"); }); ``` 在上面的示例代码中,我们使用了 Axios 库发送了一个 POST 请求到 `/api/upload` 接口,请求体中包含了一个名为 `image` 的文件参数,后端使用 Multer 中间件将文件保存到了 `uploads/` 目录下。你可以根据自己的需求来修改这个示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值