Vue【七】实现图片上传与预览

前端

图片上传

bash 复制代码
<template>
  <div class="comment-wrapper">
    <el-form :model="form" style="    padding: 20px;" label-width="80px">
      <el-form-item label="评价内容">
        <el-input v-model="form.comment_content"  type="textarea"></el-input>
      </el-form-item>
      <el-form-item label="上传图片">
        <el-upload
          action="http://localhost:8081/upload/file"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :on-success="uploadSuccess"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>

      </el-form-item>
      <el-form-item style="margin-top: 15px">
        <el-button type="primary" @click="submitForm">提交评价</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Comment",
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      img_url_list:[],
      form: {
        comment_username: window.sessionStorage.getItem("token"),
        comment_content: '',
        comment_img_url: ''
      }
    };
  },
  methods: {
    uploadSuccess(response, file, fileList) {
      this.img_url_list.push(response.data);
    },
    handleRemove(file, fileList) {
      console.log(1, this.img_url_list);
      let name = file.response.data;
      for (let i=0; i<this.img_url_list.length; i++){
        if (this.img_url_list[i] == name){
          this.img_url_list.splice(i, 1)
        }
      }
      console.log(1, this.img_url_list);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    submitForm() {
      if(this.img_url_list.length > 0){
        let str = '';
        for (var i = 0; i < this.img_url_list.length; i++) {
          str += this.img_url_list[i]+ ",";
        }
        str = str.substr(0, str.length - 1);
        this.form.comment_img_url=str;
      }
      this.$http.post("/comment/add", this.form).then(result => {
        this.$message.success("评论成功");
        this.$router.push('/order');
      })
    }
  },
  created() {
    let orderId = this.$route.query.orderId;
    this.form.order_id = orderId;

  }

}
</script>

<style scoped>
.comment-wrapper{
  margin: 15px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-radius: 15px;
  height: 500px;
}
/deep/ .el-form-item{
  width: 50%;
  margin: 15px auto;
}
/deep/ .el-textarea__inner{
  height: 150px;
}
.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
}

.avatar {
  width: 100px;
  height: 100px;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}
</style>

图片预览

bash 复制代码
 <div class="comment-img" v-for="img in item.comment_img_list">
          <img :src="img" @click="open(img)"/>
        </div>
bash 复制代码
 open(src){
      this.$alert('<img style="width: 100%" src="'+src+'"></img>', '', {
        dangerouslyUseHTMLString: true
      });
    },

后台代码

bash 复制代码
package com.wang.wangblog.controller.admin;

import com.wang.wangblog.config.Constants;
import com.wang.wangblog.model.Vo.Result;
import com.wang.wangblog.utils.MyBlogUtils;
import com.wang.wangblog.utils.ResultGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
@RequestMapping("/admin")
public class UploadController {

    @Value("${upload.path:E:\\imgs}")
    private String path;


    @PostMapping({"/upload/file"})
    @ResponseBody
    public Result upload(HttpServletRequest httpServletRequest, @RequestParam("file") MultipartFile file) throws URISyntaxException {
        String fileName = file.getOriginalFilename();
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称通用方法
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        Random r = new Random();
        StringBuilder tempName = new StringBuilder();
        tempName.append(sdf.format(new Date())).append(r.nextInt(100)).append(suffixName);
        String newFileName = tempName.toString();
        String month = new SimpleDateFormat("yyyyMM").format(new Date()) + File.separator;
        String destPath =  path + month;
        File fileDirectory = new File(destPath);
        //创建文件
        File destFile = new File(destPath + newFileName);
        try {
            if (!fileDirectory.exists()) {
                if (!fileDirectory.mkdir()) {
                    throw new IOException("文件夹创建失败,路径为:" + fileDirectory);
                }
            }
            file.transferTo(destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Result result = ResultGenerator.genSuccessResult();
        result.setData(MyBlogUtils.getHost(new URI(httpServletRequest.getRequestURL() + "")) + "/upload/" +month+ newFileName);
        return result;
    }

}
相关推荐
JUNAI_Strive_ving10 分钟前
番茄小说逆向爬取
javascript·python
看到请催我学习19 分钟前
如何实现两个标签页之间的通信
javascript·css·typescript·node.js·html5
twins352038 分钟前
解决Vue应用中遇到路由刷新后出现 404 错误
前端·javascript·vue.js
qiyi.sky1 小时前
JavaWeb——Vue组件库Element(3/6):常见组件:Dialog对话框、Form表单(介绍、使用、实际效果)
前端·javascript·vue.js
煸橙干儿~~1 小时前
分析JS Crash(进程崩溃)
java·前端·javascript
哪 吒1 小时前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
安冬的码畜日常1 小时前
【D3.js in Action 3 精译_027】3.4 让 D3 数据适应屏幕(下)—— D3 分段比例尺的用法
前端·javascript·信息可视化·数据可视化·d3.js·d3比例尺·分段比例尺
杨荧2 小时前
【JAVA开源】基于Vue和SpringBoot的洗衣店订单管理系统
java·开发语言·vue.js·spring boot·spring cloud·开源
l1x1n02 小时前
No.3 笔记 | Web安全基础:Web1.0 - 3.0 发展史
前端·http·html
Q_w77422 小时前
一个真实可用的登录界面!
javascript·mysql·php·html5·网站登录