elementui上传图片

前端:

<template>
    <el-dialog :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
        <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
            label-width="80px">
            <el-form-item label="标题" prop="title">
                <el-input v-model="dataForm.title" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item label="内容" prop="content">
                <el-input v-model="dataForm.content" placeholder="内容"></el-input>
            </el-form-item>
            <el-form-item label="图片1" prop="img1">
                <el-input v-model="dataForm.img1" placeholder="图片1"></el-input>
                <el-upload class="upload-demo" :action="imgUrl" :before-remove="beforeRemove" multiple :limit="1"
                    :on-exceed="handleExceed" :file-list="fileList1" :on-success="doc1" :on-error="handleAvatarError">
                    <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item label="图片2" prop="img2">
                <el-input v-model="dataForm.img2" placeholder="图片2"></el-input>
                <el-upload class="upload-demo" :action="imgUrl" :before-remove="beforeRemove" multiple :limit="1"
                    :on-exceed="handleExceed" :file-list="fileList2" :on-success="doc2" :on-error="handleAvatarError">
                    <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item label="图片3" prop="img3">
                <el-input v-model="dataForm.img3" placeholder="图片3"></el-input>
                <el-upload class="upload-demo" :action="imgUrl" :before-remove="beforeRemove" multiple :limit="1"
                    :on-exceed="handleExceed" :file-list="fileList3" :on-success="doc3" :on-error="handleAvatarError">
                    <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
            </el-form-item>
            <el-form-item label="点赞数" prop="dianzan">
                <el-input v-model="dataForm.dianzan" placeholder="点赞数"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
        </span>
    </el-dialog>
</template>

<script>
    export default {
        data() {
            return {
                fileList1: [],
                fileList2: [],
                fileList3: [],
                imgUrl: 'http://127.0.0.1:8080/renren-fast/uploads/local',
                visible: false,
                dataForm: {
                    id: 0,
                    title: '',
                    content: '',
                    img1: '',
                    img2: '',
                    img3: '',
                    dianzan: ''
                },
                dataRule: {
                    title: [{
                        required: true,
                        message: '标题不能为空',
                        trigger: 'blur'
                    }],
                    content: [{
                        required: true,
                        message: '内容不能为空',
                        trigger: 'blur'
                    }],
                    img1: [{
                        required: true,
                        message: '图片1不能为空',
                        trigger: 'blur'
                    }],
                    img2: [{
                        required: true,
                        message: '图片2不能为空',
                        trigger: 'blur'
                    }],
                    img3: [{
                        required: true,
                        message: '图片3不能为空',
                        trigger: 'blur'
                    }],
                    dianzan: [{
                        required: true,
                        message: '点赞数不能为空',
                        trigger: 'blur'
                    }]
                }
            }
        },
        methods: {
            handleAvatarError(res, file) {
                this.$message.error('文件太大');
            },
            handleExceed(files, fileList) {
                this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
            },
            doc1(res, file) {
                this.$message({
                    message: '上传成功',
                    type: 'success'
                });
                if (res.code == 0) {
                    this.dataForm.img1 = res.msg;
                }
            },
            doc2(res, file) {
                this.$message({
                    message: '上传成功',
                    type: 'success'
                });
                if (res.code == 0) {
                    this.dataForm.img2 = res.msg;
                }
            },
            doc3(res, file) {
                this.$message({
                    message: '上传成功',
                    type: 'success'
                });
                if (res.code == 0) {
                    this.dataForm.img3 = res.msg;
                }
            },
            beforeRemove(file, fileList) {
                return this.$confirm(`确定移除 ${ file.name }?`);
            },
            init(id) {
                this.dataForm.id = id || 0
                this.visible = true
                this.$nextTick(() => {
                    this.$refs['dataForm'].resetFields()
                    if (this.dataForm.id) {
                        this.$http({
                            url: this.$http.adornUrl(`/generator/news/info/${this.dataForm.id}`),
                            method: 'get',
                            params: this.$http.adornParams()
                        }).then(({
                            data
                        }) => {
                            if (data && data.code === 0) {
                                this.dataForm.title = data.news.title
                                this.dataForm.content = data.news.content
                                this.dataForm.img1 = data.news.img1
                                this.dataForm.img2 = data.news.img2
                                this.dataForm.img3 = data.news.img3
                                this.dataForm.dianzan = data.news.dianzan
                            }
                        })
                    }
                })
            },
            // 表单提交
            dataFormSubmit() {
                this.$refs['dataForm'].validate((valid) => {
                    if (valid) {
                        this.$http({
                            url: this.$http.adornUrl(
                                `/generator/news/${!this.dataForm.id ? 'save' : 'update'}`),
                            method: 'post',
                            data: this.$http.adornData({
                                'id': this.dataForm.id || undefined,
                                'title': this.dataForm.title,
                                'content': this.dataForm.content,
                                'img1': this.dataForm.img1,
                                'img2': this.dataForm.img2,
                                'img3': this.dataForm.img3,
                                'dianzan': this.dataForm.dianzan
                            })
                        }).then(({
                            data
                        }) => {
                            if (data && data.code === 0) {
                                this.$message({
                                    message: '操作成功',
                                    type: 'success',
                                    duration: 1500,
                                    onClose: () => {
                                        this.visible = false
                                        this.$emit('refreshDataList')
                                    }
                                })
                            } else {
                                this.$message.error(data.msg)
                            }
                        })
                    }
                })
            }
        }
    }
</script>

后端

package io.renren.upload;

import io.renren.common.utils.R;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Api(tags = "上传相关")
@RequestMapping("/uploads")
@RestController
public class UploadController {

    @ResponseBody
    @PostMapping(value="/local")
    public R testUpload(@RequestParam("file") MultipartFile file) throws IOException {
        String fileExtension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(0, originalFilename.indexOf("."));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        String format1 = format.format(new Date());
        String fileName = substring+"-"+format1 + fileExtension;
        String path ="D:/tomcat8/apache-tomcat-8.0.43/webapps/ROOT/img/";
        //检查该路径对应的目录是否存在. 如果不存在则创建目录
        File dir=new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String filePath = path + fileName;
        System.out.println("filePath: "+filePath);
        //保存文件
        File dest = new File(filePath);
        if (!(dest.exists())) {
            file.transferTo(dest);
        }
        String uurl= "http://127.0.0.1:8096/img/"+fileName;
        return R.ok(uurl);
    }

}

 

上一篇:视频参数


下一篇:c++享元模式