springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库


springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库

*hello everybody,为了让大家更快的找到自己想要的功能,我们先来看看需要完成的项目是什么样子的叭
如下:
springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第1张图片

那我们再来看看做出来的效果图是什么样子的吧(这是新增的效果图)

新增以后显示的效果:

springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第2张图片
大家可以看出,我刚刚上传的图片是可以显示的,新增的数据也是有的(如果图片显示不出来刷新一下即可),至于修改跟删除是一样的啦,只是修改会根据你的id获取你的数据显示在form表单上,这个下面我们会提的,删除等会咱也会提的哈,8要着急

springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第3张图片

好啦,废话不多说,接下来进入正题了 。。。。。。。。。。。。。。。。。。。。。。。。。。

咱们从数据库开始,因为我们的项目是要发布到服务器上去的,所有,你得把你的数据库连接一下你的服务器(前提是,你得买一个服务器,我的话,直接用的阿里云的服务器,有需要的可以去阿里云购买)

然后,你就需要安装一个docker,然后再docker里面安装mysql,tomcat啥的(这里的各类安装的命令我就不说了,我直接贴一个链接,有需要的自己看吧https://www.cnblogs.com/aikutao/p/11163333.html)
在这里插入图片描述

接下来,贴一我的数据库

第一个是goods表:

springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第4张图片

第二个是GoodsDetail表:

springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第5张图片

ok,next,我们来写后台代码吼。。。。。。。。。。。。。。。。。。。。。。。。。。springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第6张图片

这是我后台项目的整个结构

springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第7张图片

我先把pom.xml文件和application.properties给你们

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/>
    </parent>
    <groupId>com.example</groupId>
    <artifactId>goods</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>goods</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.3</version>
        </dependency>
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.16.10</version>
            </dependency>
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3</version>
        </dependency>
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.1</version>
        </dependency>

        <!-- spring boot web支持:mvc,aop... -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <!-- 过滤springboot默认嵌入式tomcat插件 -->
            <!--<exclusions>-->
            <!--<exclusion>-->
            <!--<groupId>org.springframework.boot</groupId>-->
            <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
            <!--</exclusion>-->
            <!--</exclusions>-->
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--thymeleaf模板-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <!--MyBatis依赖jar包和MySQL连接相关的jar包-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--打包添加的依赖-->
        <!--添加发布依赖-->
        <!--<dependency>-->
        <!--<groupId>org.springframework.boot</groupId>-->
        <!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
        <!--<scope>provided</scope>-->
        <!--</dependency>-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-core</artifactId>
            <version>3.0.5</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.generator</groupId>
            <artifactId>mybatis-generator-core</artifactId>
            <version>1.3.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

application.properties:

spring.datasource.url=jdbc:mysql://39.105.16.76/goods?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=sasa
server.port=9090
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
mybatis-plus.mapper-locations=classpath:mappers/*Dao.xml
logging.level.com.example.goods.mapper=debug
# url path
#server.port=8088
#server.servlet.context-path=/shipin

# thymeleaf
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.encoding=UTF-8
#spring.thymeleaf.content-type
spring.thymeleaf.servlet.content-type=text/html

# 开发阶段务必关闭缓存 (=false)
spring.thymeleaf.cache=false

#最大文件大小。值可以使用后缀“MB”或“KB”。指示兆字节或千字节大小。
spring.servlet.multipart.max-file-size=-1
# 最大请求大小可以是mb也可以是kb
spring.servlet.multipart.max-request-size=-1

#配置外部访问文件(把上传的图片视频文件放到E盘下的fileUpload文件夹下)
cbs.imagesPath=file:/E:/fileUpload/
#com.yangyouqi: ${server.port}
#spring.jmx.enabled=false






config包里面的类都是一些配置类,我直接贴出来就行。
CORSConfiguration类是一个解决前后端跨域问题的全局配置类

package com.example.goods.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;


/**
 * 解决跨域的全局配置类,推荐使用!!!
 * @author 34582
 *
 */
@Configuration
public class CORSConfiguration {
     
	
	@Bean
    public CorsFilter corsFilter() {
     
        CorsConfiguration config = new CorsConfiguration();
	      config.addAllowedOrigin("*");

	      config.setAllowCredentials(true);
	      config.addAllowedMethod("*");
	      config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration("/**", config);

        return new CorsFilter(configSource);
    }

    

}

WebAppConfig类是与图片上传有关系的类:

package com.example.goods.config;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.unit.DataSize;
import org.springframework.web.servlet.config.annotation.*;

import javax.servlet.MultipartConfigElement;

//上传配置类
//图片放到/F:/fileUpload/后,从磁盘读取的图片数据scr将会变成images/picturename.jpg的格式
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {
     
//public class WebAppConfig extends WebMvcConfigurationSupport {
     
    /**
     * 在配置文件中配置的文件保存路径
     */
    @Value("${cbs.imagesPath}")
    private String mImagesPath;

    @Bean
    public MultipartConfigElement multipartConfigElement(){
     
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //文件最大KB,MB
        factory.setMaxFileSize(DataSize.parse("1024MB"));
        //设置总上传数据总大小
        factory.setMaxRequestSize(DataSize.parse("1024MB"));
        return factory.createMultipartConfig();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
     
        if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){
     
            String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();
            System.out.print("1.上传配置类imagesPath=="+imagesPath+"\n");
            if(imagesPath.indexOf(".jar")>0){
     
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            }else if(imagesPath.indexOf("classes")>0){
     
                imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";
            mImagesPath = imagesPath;
        }
        System.out.print("imagesPath============="+mImagesPath+"\n");
        //LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath============="+mImagesPath+"\n");
        registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);
        // TODO Auto-generated method stub
        System.out.print("2.上传配置类mImagesPath=="+mImagesPath+"\n");
        super.addResourceHandlers(registry);
    }

}

然后util包里面全部都是工具类,返回错误码的类:

Msg类:

package com.example.goods.util;

public class Msg {
     
    public int getCode() {
     
        return code;
    }

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

    public String getMsg() {
     
        return msg;
    }

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

    public Object getData() {
     
        return data;
    }

    public void setData(Object data) {
     
        this.data = data;
    }
    
/*
返回错误码
 */
    private int code;
    /*
    返回消息
     */
    private String msg;
    /*
    返回数据
     */
    private Object data;
}

ResultUtil类:

package com.example.goods.util;

public class ResultUtil {
     
    public static Msg success(Object data){
     
        Msg msg=new Msg();
        msg.setCode(0);
        msg.setMsg("请求成功!!");
        msg.setData(data);
        return msg;
    }

    public static Msg fail(int code,String message){
     
        Msg msg=new Msg();
        msg.setCode(code);
        msg.setMsg(message);
        msg.setData(message);
        return msg;
    }
}

pojo实体包:

Goods商品实体类:

package com.example.goods.pojo;

import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author yy
 * @since 2019-11-21
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("Goods")
public class Goods extends Model<Goods> {
     

    private static final long serialVersionUID = 1L;

    private Integer goodsid;

    @TableField("goodsName")
    private String goodsName;

    @TableField("goodsPrice")
    private BigDecimal goodsPrice;

    private String imageurl;

    private Integer status;

    private String goodssp;

    @TableId(value = "id", type = IdType.AUTO)
    private Integer id;

private GoodsDetail eu;

    public GoodsDetail getEu() {
     
        return eu;
    }

    public void setEu(GoodsDetail eu) {
     
        this.eu = eu;
    }

    @Override
    protected Serializable pkVal() {
     
        return this.id;
    }

}

GoodsDetail商品品牌类型类:

package com.example.goods.pojo;

import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

/**
 * <p>
 * 
 * </p>
 *
 * @author yy
 * @since 2019-11-21
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("GoodsDetail")
public class GoodsDetail extends Model<GoodsDetail> {
     

    private static final long serialVersionUID = 1L;

    @TableId(value = "goodsdetailid", type = IdType.AUTO)
    private Integer goodsdetailid;

    private String goodtye;

    private Integer goodsid;


    @Override
    protected Serializable pkVal() {
     
        return this.goodsdetailid;
    }

}

ShiPin类:(这个是图片上传的时候在商品类新增加的类,因为我是逆向工程直接生成的,所以不能在原本的goods实体类新增,得另外写一个实体类放我新增的字段)

package com.example.goods.pojo;

public class ShiPin {
     

    private int id;
    private String url;

    public int getId() {
     
        return id;
    }

    public void setId(int id) {
     
        this.id = id;
    }

    public String getUrl() {
     
        return url;
    }

    public void setUrl(String url) {
     
        this.url = url;
    }

}

mapper包:

GoodsMapper商品接口(其实你们可以用mybatis-plus自带的方法来着,但是我对那个不咋熟悉,所有有的方法还是我自己自定义的):

package com.example.goods.mapper;

import com.example.goods.pojo.Goods;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author yy
 * @since 2019-11-21
 */
public interface GoodsMapper extends BaseMapper<Goods> {
     
//查看所有的接口
    public List<Goods> selectall();
//根据id查询status
    public Goods selectid(int id);
    //修改的接口
    public int update(Goods goods);
}

ShiPinDao接口(图片上传的接口):

package com.example.goods.mapper;
import com.example.goods.pojo.ShiPin;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Component;

import java.util.List;

@Mapper
@Component
public interface ShiPinDao {
     

    //插入
    @Insert({
     "insert into Goods (name,lujing,url) values (#{name},#{lujing},#{url})"})
    public int insertUrl(@Param("name")String name,@Param("lujing")String lujing,@Param("url")String url);

    //查询
    @Select("select * from Goods")
    public List<ShiPin> selectShipin();
}

servie包:

GoodsService类:

package com.example.goods.service;

import com.example.goods.pojo.Goods;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author yy
 * @since 2019-11-21
 */
public interface GoodsService extends IService<Goods> {
     
    //查看所有的接口
    public List<Goods> selectall();
    //根据id查询status
    public Goods selectid(int id);
    //修改的接口
    public int update(Goods goods);

}

ShiPinService类:

package com.example.goods.service;

import com.example.goods.mapper.ShiPinDao;
import com.example.goods.pojo.ShiPin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
@Component
public class ShiPinService {
     

    @Autowired
    private ShiPinDao shiPinDao;

    //插入
    public int insertUrl(String name,String lujing,String url){
     
        System.out.print("开始插入=name=="+name+"\n");
        System.out.print("开始插入=lujing=="+lujing+"\n");
        System.out.print("开始插入=url=="+url+"\n");
        int jieguo=shiPinDao.insertUrl(name,lujing,url);
        System.out.print("插入结果==="+jieguo+"\n");
        return jieguo;
    }
    //查询
    public List<ShiPin> selectShipin(){
     
        List<ShiPin> shipins=shiPinDao.selectShipin();
        return  shipins;
    }
}


service的实现类GoodsServiceImpl:

package com.example.goods.service.impl;

import com.example.goods.pojo.Goods;
import com.example.goods.mapper.GoodsMapper;
import com.example.goods.service.GoodsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yy
 * @since 2019-11-21
 */
@Service

public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, Goods> implements GoodsService {
     
@Autowired
GoodsMapper gm;
    @Override
    public List<Goods> selectall() {
     
        return gm.selectall();
    }

    @Override
    public Goods selectid(int id) {
     
        return gm.selectid(id);
    }

    @Override
    public int update(Goods goods) {
     
        return gm.update(goods);
    }

}

最后,controller层:
GoodsController商品类:

package com.example.goods.controller;


import com.example.goods.pojo.Goods;
import com.example.goods.service.GoodsService;
import com.example.goods.util.Msg;
import com.example.goods.util.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yy
 * @since 2019-11-21
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
     
@Autowired
    GoodsService gs;
@GetMapping(value = "/selectall")
    public Msg selectall(){
     
    List<Goods> list=gs.selectall();
    System.out.println(list+"selectall");
    return ResultUtil.success(list);
}
//因为我只在后台判断了,只有下架才可以删除,所以在前端如果你的状态的上架的状态是不可以删除的,必须改成下架才可以删除,到时候你们也可以在前端也判断一下
@DeleteMapping(value = "/delete")
    public Msg delete(int id){
     
Goods list=gs.selectid(id);
    System.out.println(list+"aaaaaa");
int g=list.getStatus();
    System.out.println(g+"gggggggg");
if(g==2) {
     
    boolean num=gs.removeById(id);
    if (num) {
     
        System.out.println("删除成功");
        return ResultUtil.success(num);
    } else {
     
        System.out.println("删除失败");
    }
}else if(g==1){
     
    System.out.println("请先下架");
    return ResultUtil.fail(101,"请先下架");
}
    return ResultUtil.success(list);
}

@PostMapping(value = "/save")
    public Msg save(@RequestBody Goods goods){
     
    Goods g=new Goods();
    g.setGoodsid(goods.getGoodsid());
    g.setGoodsName(goods.getGoodsName());
    g.setStatus(goods.getStatus());
    g.setGoodsPrice(goods.getGoodsPrice());
    g.setImageurl(goods.getImageurl());
    g.setGoodssp(goods.getGoodssp());
    boolean num=gs.save(g);
    if(num){
     
        System.out.println("新增成功");
        return ResultUtil.success(g.getId());
    }else{
     
        System.out.println("新增失败");
    }
    return ResultUtil.success(g.getId());
}


    @PutMapping(value = "/update")
    public Msg updatee(@RequestBody Goods goods){
     
        Goods g=new Goods();
        g.setId(goods.getId());
        g.setGoodsid(goods.getGoodsid());
        g.setGoodsName(goods.getGoodsName());
        g.setStatus(goods.getStatus());
        g.setGoodsPrice(goods.getGoodsPrice());
        g.setImageurl(goods.getImageurl());
        g.setGoodssp(goods.getGoodssp());
        int num=gs.update(g);
        if(num>0){
     
            System.out.println("修改成功");
            return ResultUtil.success(num);
        }else{
     
            System.out.println("修改失败");
        }
        return ResultUtil.success(num);
    }
}


FileUploadController图片上传的controller类:

package com.example.goods.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FileUploadController {
     

    //访问路径为:http://localhost:8080/file

    @RequestMapping("/file")

    public String file(){
     
        System.out.print("================请求路径===跳转file页面====="+"\n");
        return "/file";

    }

//    @RequestMapping("/shangchuan")
//
//    public String shangchuan(){
     
//        System.out.print("================请求路径===跳转index页面====="+"\n");
//        return "/index";
//
//    }
}

MyfileCOntroller图片上传的controller类:

package com.example.goods.controller;

import com.example.goods.pojo.ShiPin;
import com.example.goods.service.ShiPinService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Controller
//@RequestMapping("/file")
public class MyfileCOntroller {
     

    @Autowired
    private ShiPinService shiPinService;

    private String  url;

    @RequestMapping(value="/uploadFile",produces="application/json;charset=UTF-8")
    @ResponseBody
    public String uploadFile(@RequestParam("fileName") MultipartFile file) {
     

        System.out.print("上传文件==="+"\n");
        //判断文件是否为空
        if (file.isEmpty()) {
     
            return "上传文件不可为空";
        }


        // 获取文件名
        String fileName = file.getOriginalFilename();
//        System.out.print("上传的文件名为: "+fileName+"\n");

    //    fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        System.out.print("(加个时间戳,尽量避免文件名称重复)保存的文件名为: "+fileName+"\n");


        //加个时间戳,尽量避免文件名称重复
        String path = "/var/fdfs/storage/" + fileName;
        //String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
        //文件绝对路径
        System.out.print("保存文件绝对路径"+path+"\n");

        //创建文件路径
        File dest = new File(path);

        //判断文件是否已经存在
        if (dest.exists()) {
     
            return "文件已经存在";
        }

        //判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
     
            dest.getParentFile().mkdir();
        }

        try {
     
            //上传文件
            file.transferTo(dest); //保存文件
            System.out.print("保存文件路径"+path+"\n");
            //url="http://你自己的域名/项目名/images/"+fileName;//正式项目
         //   url="http://localhost:9090/images/"+fileName;//本地运行项目

          //  int jieguo= shiPinService.insertUrl(fileName,path,url);
          //  System.out.print("插入结果"+jieguo+"\n");
            System.out.print("保存的完整url===="+url+"\n");

        } catch (IOException e) {
     
            return "上传失败  " + e.getMessage();
        }

        return "上传成功,文件url=="+url;
    }

    //查询
    @RequestMapping("/chaxun")
    public String huizhiDuanxin(Model model){
     
        System.out.print("查询视频"+"\n");
        List<ShiPin> shipins=shiPinService.selectShipin();
        System.out.print("查询到的视频数量=="+shipins.size()+"\n");
        model.addAttribute("Shipins", shipins);

        return "/filelist";
    }

}

噢,对了对了,还有xml文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.goods.mapper.GoodsMapper">
    <resultMap id="eu" type="com.example.goods.pojo.Goods">
        <id column="id" property="id"/>
        <result column="goodsid" property="goodsid"/>
        <result column="goodsName" property="goodsName"/>
        <result column="goodsPrice" property="goodsPrice"/>
        <result column="imageurl" property="imageurl"/>
        <result column="status" property="status"/>
        <result column="goodssp" property="goodssp"/>
        <association property="eu" javaType="com.example.goods.pojo.GoodsDetail">
            <id column="goodsdetailid" property="goodsdetailid"/>
            <result column="goodtye" property="goodtye"/>
            <result column="goodsid" property="goodsid"/>
        </association>
    </resultMap>
    <select id="selectall" resultMap="eu">
select g.id,g.goodsid,g.goodsName,g.goodsPrice,g.imageurl,g.status,g.goodssp,d.goodtye from Goods g join GoodsDetail d on g.goodsid=d.goodsid
    </select>
    <select id="selectid" resultType="com.example.goods.pojo.Goods">
        select status from Goods where id=#{id}
    </select>

    <update id="update" parameterType="com.example.goods.pojo.Goods">
        update Goods set goodsid=#{goodsid},goodsName=#{goodsName},goodsPrice=#{goodsPrice},imageurl=#{imageurl},status=#{status},goodssp=#{goodssp} where id=#{id}
    </update>
</mapper>

好了,后台代码到这里就结束了,咱们进入前端哈。。。。。。。。。。。。。springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第8张图片

前端我们用的是vue,先下载一个WebStorm ,new一个vue.js,至于怎么新建项目,我这里不多说。我直接贴前端代码。

<template>
  <div>
    <div class="usertable">
      <el-row class="usersavebtn">
        <el-button type="success" @click="handleSave()">新增</el-button>
      </el-row>
      <el-table :data="tableData" style="width: 1000px" class="warning-row">
        <el-table-column prop="id" label="序号" width="180"></el-table-column>
        <el-table-column prop="eu.goodtye" label="商品品牌" width="180"></el-table-column>
        <el-table-column prop="goodsName" label="商品名称"></el-table-column>
        <el-table-column prop="goodsPrice" label="商品价格"></el-table-column>
        <el-table-column  label="图片" width="280">
          <template slot-scope="scope">
            <img v-bind:src="scope.row.imageurl" width="150px" height="100px"/>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <div v-if="scope.row.status==1">
              <span style="margin-left: 10px">上架</span>
            </div>
            <div v-if="scope.row.status==2">
              <span style="margin-left: 10px">下架</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="goodssp" label="商铺"></el-table-column>
        <el-table-column label="操作" width="280">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" size="small" type="primary" icon="el-icon-edit">编辑</el-button>
            <el-button @click="handleDelete(scope.row.id)" size="small" type="primary" icon="el-icon-delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑模块 dialog 组件 -->
      <el-dialog title="编辑信息" :visible.sync="dialogFormVisible" center @open="dialogOpened">
        <el-form :model="form" :rules="rules" ref="form">
          <el-form-item label="编号" :label-width="formLabelWidth" prop="id" v-show="false">
            <el-input v-model="form.id" autocomplete="off" style="width:50%"></el-input>
          </el-form-item>
          <el-form-item label="商品名称" :label-width="formLabelWidth" prop="executor">
            <el-input v-model="form.goodsName" autocomplete="off" style="width:50%"></el-input>
          </el-form-item>
          <el-form-item label="商品品牌" :label-width="formLabelWidth" prop="executor">
            <el-input v-model="form.goodsid" autocomplete="off" style="width:50%"></el-input>
          </el-form-item>
          <el-form-item label="商品价格" :label-width="formLabelWidth" prop="description">
            <el-input v-model="form.goodsPrice" autocomplete="off" style="width:50%"></el-input>
          </el-form-item>
          <!--<el-form-item label="商品图片" prop="imageUrl" enctype="multipart/form-data">-->
            <!--<el-upload class="upload-demo" ref="upload" :action="importFileUrl" :auto-upload="false" :onError="uploadError" :onSuccess="uploadSuccess" :beforeUpload="beforeAvatarUpload" list-type="picture">-->
              <!--<el-button slot="trigger" size="small" type="primary">选取文件</el-button>-->
            <!--</el-upload>-->
          <!--</el-form-item>-->

          <form action="http://39.105.16.76:8080/goodsproject/uploadFile" id="hzh" method="post" enctype="multipart/form-data">
            <input type="file" id="file" name="fileName"/>
          </form>


          <el-form-item label="商品状态" :label-width="formLabelWidth" prop="createdate">
            <select v-model="form.status" style="width:200px;height: 30px;margin-top: 5px;margin-bottom: 5px;margin-left: 10px">
              <option value="">请选择商品状态</option>
              <option v-for="item in kindList" v-bind:value="item.id" v-text="item.name" ></option>
            </select>
          </el-form-item>
          <el-form-item label="商铺" :label-width="formLabelWidth" prop="createdate">
            <el-input v-model="form.goodssp" autocomplete="off" style="width:50%"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="onCancel('form')">取 消</el-button>
          <el-button type="primary" @click="onSubmit('form')">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<style>
  .warning-row {
     
    background: #67C23A;
  }


  .usertable {
     
    margin: 0 auto;
    width: 60%;
    position: relative; }
  .usersavebtn{
     
    height: 50px;
    float: left; }
</style>

<script>
  const axios = require("axios");


  export default {
     
    name: "UserMessage",
    data() {
     
      return {
     
        executor: '',
        tableData: [],
        dialogFormVisible: false,
        formLabelWidth: '120px',
        kindList:[{
     name:"上架",id:1},{
     name:"下架",id:2}],
        form: {
     
          id: '',
          goodsid: '',
          goodsName: '',
          lujing:'',
          url:'',
          goodsPrice: '',
          imageurl: '',
          delivery: false,
          type: [],
          status: '',
          goodssp: ''
        },// 表单验证规则
        rules: {
     
          goodsName: [ {
      required: true, message: '请输入商品的名称', trigger: 'blur' },
            {
      min: 2, max: 32, message: '长度在 2 到 32 个字符', trigger: 'blur' }
          ],
          goodsPrice: [{
      required: true, message: '请输入商品的价格', trigger: 'blur' }],
          status: [{
      required: true, message: '请输入商品的状态', trigger: 'blur' }],
          goodsid: [{
      required: true, message: '请输入商品的品牌', trigger: 'blur' }]
        }
      }
    },
    created: function() {
     
      alert("0")
      this.init();

    },
    methods: {
     
      dialogOpened: function () {
     
      },
      handleDelete: function (i) {
     
        alert(i)
        var vm = this
        axios
          .delete('http://39.105.16.76:8080/goodsproject/goods/delete?id=' + i)
          .then(function (response) {
     
            alert('删除成功')
            vm.init(vm)
          })
          .catch(function (error) {
     
          })
      },
      init: function (h) {
     
        var app = this;
        var a = h == undefined ? app : h
        console.log('init')
        axios
          .get("http://39.105.16.76:8080/goodsproject/goods/selectall")
          .then(function (response) {
     
// handle success
            console.log("============", response.data)
            a.tableData = response.data.data;
            console.log("response", response);
          })
          .catch(function (error) {
     
// handle error
            console.log(error);
          });
      },
      handleEdit: function (row) {
     
        this.dialogFormVisible = true
        this.form = row
      },
      onSubmit: function (name) {
     
        var id = this.form.id
        var vm = this
        alert(id + "id")
        this.$refs[name].validate(valid => {
     
          if (valid) {
     
            let file = document.getElementById("file").files[0]
            this.form.imageurl="http://39.105.16.76:8080/pictures/"+file.name
            //关于这个路径是怎么生成的,请看https://blog.csdn.net/pengge0727/article/details/81382589
            if (id == "") {
     
              console.log('-------新增-------')

              axios
                .post('http://39.105.16.76:8080/goodsproject/goods/save', this.form)
                .then(function (response) {
     
                  console.log(file)
                  document.getElementById("hzh").submit();
                   vm.init(vm)

                })
                .catch(function (error) {
     
                  console.log(error)
                })
            }
            else {
     
              console.log('-------修改-------')
              axios
                .put('http://39.105.16.76:8080/goodsproject/goods/update', this.form)
                .then(function (response) {
     
                  document.getElementById("hzh").submit();
                  this.tableData = response.data
                })
                .catch(function (error) {
     
                  console.log(error)
                })
            }
            alert('验证成功,提交成功!')
            this.dialogFormVisible = false
          } else {
     
            alert('请完成必填项')
          }
        })
      },
      onCancel: function(name) {
     
        this.dialogFormVisible = false
      },
      handleSave: function() {
     
        this.dialogFormVisible = true
        this.form = {
     
          id: '',
          goodsid: '',
          goodsName: '',
          goodsPrice: '',
          imageurl: '',
          delivery: false,
          type: [],
          status: '',
          goodssp: ''
        }
      },
      addImage: function () {
     
        let self = this;
        if (self.$refs.new_image.files.length !== 0) {
     
          var formData = new FormData()
          formData.append('image_data', self.$refs.new_image.files[0]);
          //单个文件进行上传
          self.$ajax.post('http://39.105.16.76:8080/goodsproject/goods/addImage', formData, {
     
            headers: {
     
              "Content-Type": "multipart/form-data"
            }
          }).then(response => {
     

          })
        }
      }
    }
  }
</script>

<style scoped>

</style>

对了,记得在main.js里面写这些

import axios from 'axios'
import VueAxios from 'vue-axios'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.prototype.$ajax = axios

提醒一下:因为我只在后台判断了,只有下架才可以删除,所以在前端如果你的状态的上架的状态是不可以删除的,必须改成下架才可以删除,到时候你们也可以在前端也判断一下,还有,新增的时候他会跳转一个页面,你直接后退到原页面,然后刷新一下就行

到现在为止,代码差不多就写完了,接下来就要打包项目到服务器了,前台打包直接双击bulid,他自己就会打包

springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第9张图片


然后他会生成一个dist,把dist里面的文件拖出来,用一个文件夹装起来,放在你服务器的tomcat里面就ok,至于后台的话,就直接打包一个war包,放在服务器的tomcat里面就行(如果实在不会,可以百度的)

在这里插入图片描述

最后的访问路径就是(这是我项目的路径)http://39.105.16.76:8080/gd/index.html#/(如果我服务器没有过期,应该都是能访问到的)

ok,fine,今天的代码到这里已经全部分享完了,如果有问题私信我,也欢迎指正啦,啾咪。springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库_第10张图片

你可能感兴趣的:(springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库)