springboot+Vue (element ui)图片上传(连同数据库中的数据)

   //后端代码
    //上传图片
    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> uploadToUser(@RequestParam("file") MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        FileOutputStream out = null;
        try {
            String fileName = file.getOriginalFilename();
            if (fileName.indexOf("\\") != -1) {
                fileName = fileName.substring(fileName.lastIndexOf("\\"));
            }
            // 获取文件存放地址
            String filePath = "D:\\Project\\manager-api\\src\\main\\resources\\static\\images\\";
            File f = new File(filePath);

            if (!f.exists()) {
                f.mkdirs();// 不存在路径则进行创建
            }
            // 重新自定义文件的名称
            filePath = filePath + fileName;
            out = new FileOutputStream(filePath);
            out.write(file.getBytes());
            out.flush();
            out.close();
            map.put("1", "ok");
            map.put("realUrl",fileName);
            Thread.sleep(1000);
            return map;
        } catch (Exception e) {
            map.clear();
            map.put("2", "error");
            return map;
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //添加产品图片至数据库
    @PostMapping("/addProductImage")
    public ServerResponse addProductImage(@RequestBody SFile sFile){
        int i = sProductService.addProductImage(sFile);
        if(i>0){
            return ServerResponse.createServerResponseBySuccess("上传成功");
        }else {
            return ServerResponse.createServerResponseByFail("上传失败");
        }
    }

前端:

<!-- 图片列表 -->
      <span v-for="(image,index) in imageData">
        <img
          class="el-upload-list__item-thumbnail"
          :src="url+image.realUrl" alt=""
          width="240px"
          height="200px"
          >
          <span class="el-upload-list__item-actions">
            <span
              class="el-icon-zoom-in"
              @click="handlePictureCardPreview(image.realUrl)"
            >
            </span>
            <span
              class="el-icon-delete"
              @click="deleteProductImage(image.id,image.realUrl)"
            >
            </span>
        </span>
      </span>
      <el-upload  
        class="upload-demo"
        :action="action"
        :headers="{
                token: token,
              }"
        :on-success="uploadProductImage"
        :on-error="uploadError">
          <el-button type="primary" round >上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
      </el-upload>
      <!-- 图片 -->
      <el-dialog :visible.sync="dialogVisible" width="800px">
        <center>
        <img   width="70%" :src="dialogImageUrl" alt="">
        </center>
      </el-dialog>
<script>
import {getProductContentList,addProductDetail,updateProductDetail,deleteProductDetailById,getProductImage,addProductImage,deleteProductImage} from '@/api/productDetail'
import { getToken } from '@/utils/auth';//记得往后端传token
import { url,action }from '@/utils/request'
export default {
  components: { image },
  name: 'Product',
  data() {
    return {
      url:url,
      action:action,

      token: getToken('token') || '',
      dialogImageUrl: '',
      dialogVisible: false,

      imageData:[],

      contentId:'',
      name:'',
      tableData:[],
      addDialogVisible:false,
      updateDialogVisible:false,
      addProductDetailForm: {
        id:"",
        title: '',
        detail: '',
        description:'',
        content_id: ''
      },
    }
  },
  created() {
      //产品详情
      this.getProductContentList();
      //产品图片
      this.getProductImage();
  },
  methods: {

    //放大图片
    handlePictureCardPreview(file) {
      this.dialogImageUrl = this.url+file;
      this.dialogVisible = true;
    },

    //图片详情列表
    getProductImage(){
      var id = this.$route.params.contentId;
      new Promise((resolve, reject) => {
            getProductImage({ id: id }).then(response => {
            const { data } = response
            this.imageData = data;
            }).catch(error => {
            reject(error)
            })
        })
    },

    //上传成功后,添加到数据库
    uploadProductImage(file){
      var productId = this.$route.params.contentId;
      var fileRealUrl = "/images/"+file.realUrl;
      addProductImage({ productId: productId ,name:this.name,realUrl:fileRealUrl}).then(res => {
        //上传成功
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: res.msg
          })
        }
        //上传失败
        if (res.code === 601) {
          this.$message({
            type: 'error',
            message: res.msg
          })
        }
        //上传操作后 重新查询数据
        this.getProductImage();
      }).catch(res => {

      })
    },

    //上传失败
    uploadError(){
      console.log("上传失败");
    },

    //删除图片
    deleteProductImage(id,realUrl){
        this.$confirm('是否要删除该产品图片?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteProductImage({ id: id ,realUrl : realUrl}).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功'
            })
            this.getProductImage()
          }
        }).catch(res => {

        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    //产品详情列表
    getProductContentList(){
          this.contentId= this.$route.params.contentId;
          this.addProductDetailForm.content_id = this.contentId;
          this.name = this.$route.params.name;
          this.addProductDetailForm.description = this.name;
          new Promise((resolve, reject) => {
            getProductContentList({ content_id: this.contentId }).then(response => {
            const { data } = response
            this.tableData = data
            //this.dialogImageUrl = data.
            }).catch(error => {
            reject(error)
            })
        })
    },

js:

import request from '@/utils/request'

//获取产品详情列表
export function getProductContentList(data) {
    return request({
    url: '/productCenter/getProductContentList',
    method: 'get',
    params: data
    })
}

//添加产品详情
export function addProductDetail(data) {
    return request({
        url: '/serviceItems/add',
        method: 'post',
        data: data
    })
}    

//修改产品详情
export function updateProductDetail(data) {
    return request({
        url: '/serviceItems/update',
        method: 'post',
        data: data
    })
}   

//删除产品详情
export function deleteProductDetailById(data) {
    return request({
        url: '/serviceItems/delete',
        method: 'get',
        params: data
    })
}

//根据产品id获取对应的产品图片
export function getProductImage(data) {
    return request({
    url: '/productCenter/getProductImage',
    method: 'get',
    params: data
    })
}

//添加产品详情图片
export function addProductImage(data) {
    return request({
    url: '/productCenter/addProductImage',
    method: 'post',
    data: data
    })
}

//删除产品图片
export function deleteProductImage(data) {
    return request({
        url: '/productCenter/deleteProductImage',
        method: 'get',
        params: data
    })
}

ServerResponse类:

package com.haiot.commen;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

/**
 * 服务端响应对象
 */
//注解:对象中不是空值的属性才会保留
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class ServerResponse<T> {

    private int status;//状态 0:成功   !0:各种错误
    private String msg;//接口的返回信息
    private T data;//接口返回给前端的数据
    private int code;   // 状态码

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    private ServerResponse(){

    }

    private ServerResponse(int status){
        this.status=status;
    }
    //status不为0,返回错误信息
    private ServerResponse(int status,String msg){
        this.status=status;
        this.msg=msg;
    }
    private ServerResponse(int code, int status,String msg){
        this.code = code;
        this.status = status;
        this.msg = msg;
    }
    //status为0,返回数据
    private ServerResponse(int status,T data){
        this.status=status;
        this.data=data;
    }
    //status为0,返回数据和信息
    private ServerResponse(int status,String msg,T data){
        this.status=status;
        this.msg=msg;
        this.data=data;
    }

    public ServerResponse(int code, int status, String msg, T data) {
        this.status = status;
        this.msg = msg;
        this.data = data;
        this.code = code;
    }

    public ServerResponse(String msg, int code) {
        this.msg = msg;
        this.code = code;
    }

    /**
     * 判断接口是否成功调用
     */
    @JsonIgnore
    public boolean isSuccess(){
        return this.status==ResponseCode.SUCCESS;
    }

    //接口调用成功
    public static ServerResponse  createServerResponseBySuccess(){
        return new ServerResponse<>(ResponseCode.SUCCESS);
    }
    public static<T> ServerResponse  createServerResponseBySuccess(T data){
        return new ServerResponse<>(ResponseCode.SUCCESS,data);
    }
    public static ServerResponse  createServerResponseBySuccess(String msg){
        return new ServerResponse<>(200, ResponseCode.SUCCESS,msg);
    }

    public static<T> ServerResponse  createServerResponseBySuccess(String msg,T data){
        return new ServerResponse<>(200, ResponseCode.SUCCESS, msg, data);
    }

    //调用失败
    public static ServerResponse createServerResponseByFail(){
        return new ServerResponse<>(ResponseCode.ERROR);
    }
    public static ServerResponse createServerResponseByFail(String msg){
        return new ServerResponse<>(ResponseCode.ERROR,msg);
    }
    public static ServerResponse createServerResponseByFail(String msg, int code){
        return new ServerResponse<>(msg, code);
    }
    public static ServerResponse createServerResponseByFail(int status){
        return new ServerResponse<>(status);
    }
    public static ServerResponse createServerResponseByFail(int status,String msg){
        return new ServerResponse<>(status,msg);
    }

    public int getStatus() {
        return status;
    }

    public void setStatus(int status) {
        this.status = status;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    @Override
    public String toString() {
        return "ServerResponse{" +
                "status=" + status +
                ", msg='" + msg + '\'' +
                ", data=" + data +
                '}';
    }
}

猜你喜欢

转载自blog.csdn.net/KuKu_Nao/article/details/119904883
今日推荐