精华内容
下载资源
问答
  • 本文实例讲述了vue实现的上传图片数据库并显示到页面功能。分享给大家供大家参考,具体如下: 1、点击上传图片,弹出选择图片选项框。 页面代码: 上传图片 <input type=file name=avatar id=avatar multiple=...
  • vue上传图片数据库并显示到页面

    万次阅读 2017-12-24 21:01:22
    1、点击上传图片,弹出选择图片...div class="form-signin-heading" id="btnUpload" @change="upload">上传图片div> input type="file" name="avatar" id="avatar" multiple="multiple" @change="upload"> img :src=
    1、点击上传图片,弹出选择图片选项框。
    
        页面代码:
    <div class="form-signin-heading" id="btnUpload" @change="upload">上传图片</div>
    <input type="file" name="avatar" id="avatar" multiple="multiple" @change="upload">
    <img :src="'http://localhost:8888'+item.photos_url"  alt=""/>

    由于我们要设置上传图片的样式,所以把input隐藏,并要做如下操作把input的点击事件给div框:

    mounted: function () {
      var upload = document.getElementById("btnUpload");
      var avatar = document.getElementById("avatar");
      upload.onclick =function(){
        avatar.click(); //注意IE的兼容性
      };
    }
    2、在api接口的controller层加入两个文件,命名自己定,如:

    upFile.js
    let  multer=require('multer');
    let storage = multer.diskStorage({
        //设置上传后文件路径,uploads文件夹会自动创建。
        destination: function (req, file, cb) {
            cb(null, './public/uploads')
        },
        //给上传文件重命名,获取添加后缀名
        filename: function (req, file, cb) {
            let fileFormat = (file.originalname).split(".");
            cb(null, file.fieldname + '-' + Date.now() + "." + fileFormat[fileFormat.length - 1]);
        }
    });
    //添加配置文件到multer对象。
    let upload = multer({
        storage: storage
    });
     
    
    module.exports = upload;
     
    upFileController.js 
    
    var muilter = require('./upFile.js');
    //multersingle()中的名称必须是表单上传字段的name名称。
    var upload=muilter.single('file');
    function dataInput(req, res) {
        upload(req, res, function (err) {
            //添加错误处理
            if (err) {
                return  console.log(err);
            }
            //文件信息在req.file或者req.files中显示。
            let photoPath = req.file.path;
            photoPath = photoPath.replace(/public/,"");//将文件路径中的public\去掉,否则会和静态资源配置冲突
            //photoPath存入数据库即可
            console.log(photoPath);
            res.send(photoPath);
        });
    }
    
    module.exports = {
        dataInput
    };
    3、在页面中将图片的地址存到数据库
    upload: function (e) {
            var that = this;
            let formData = new window.FormData();
            let file = e.target.files[0];
            formData.append('file',file);//通过appendform对象添加数据
            //利用split切割,拿到上传文件的格式
            var src = file.name,
              formart = src.split(".")[1];
            //使用if判断上传文件格式是否符合
            if (formart == "jpg" || formart == "png" ||
              formart == "docx" || formart == "txt" ||
              formart == "ppt" || formart == "xlsx" ||
              formart == "zip" || formart == "rar" ||
              formart == "doc") {
              //只有满足以上格式时,才会触发ajax请求
              this.$axios.post(this.$api.personalCenter.upFile,formData).then(function (res) {
                that.upFileData = res.data;
              }).then(function (res) {
                var params = {
                  photos_url: that.upFileData,
                  photo_des: ''
                };
    //            console.log(params.photos_url,'photos_url')
                that.$axios.post(that.$api.personalCenter.wallAdd,qs.stringify(params)).then(function (res) {
                  console.log(res.data);
                  that.$options.methods.imgList.bind(that)();
                }).catch(function (err) {
                  console.log(err);
                  console.log("请求出错");
                })
              })
            } else {
              alert("文件格式不支持上传");
            }
          }


     
    

    展开全文
  • 本文实例为大家分享了vue实现图片上传到后台的具体代码,供大家参考,具体内容如下 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title>...
  • 图片上传 前台代码 上传图片表单部分 <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body> <el-form ref="form" :model="form" :rules="rules" label-width="80px" enctype=...

    图片上传

    前台代码

    上传图片表单部分

    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
          <el-form ref="form" :model="form" :rules="rules" label-width="80px" enctype="multipart/form-data">
            
          
           <el-form-item label="文件" prop="file">
            <img :src="form.data" style="width:50%;height:50%"  >
              <input type="file" id="file_input" >
         
            </el-form-item>  
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancel">取 消</el-button>
            <el-button @click="downloadfile">下载</el-button>
          </div>
        </el-dialog>
    
    表单提交方法中获取file对象并放入formData 中传到后台
    
    var formData = new FormData();
                 formData.append('file', document.getElementById('file_input').files[0]);
                addBin(formData).then(response => {
                  if (response.code === 200) {
                    this.msgSuccess("新增成功");
                    this.open = false;
                    this.getList();
                  }
                });
    
    // 新增
    export function addBin(data) {
      console.log(data.file)
      return request({
        url: '/system/bin',
        method: 'post',
        data: data
      })
    }
    

    后台代码

    获取mysql数据库链接,调用执行insert方法

    public Connection getConnection() throws Exception{
    
    
    
            String url = "jdbc:mysql://***.***.**.***:3306/***?characterEncoding=utf-8&serverTimezone=UTC";
    
            String user = "**";
    
            String password = "**";
    
            Class.forName("com.mysql.cj.jdbc.Driver");
    
            Connection conn = DriverManager.getConnection(url, user, password);
    
            return conn;
    
        }
        //增加图片
        public void save(File file) throws Exception{
    
            Connection conn = getConnection();
    
            String sql = "insert into tab_bin (filename,data) values(?,?)";
    
            PreparedStatement prest = conn.prepareStatement(sql);
            String filename=file.getName();
            prest.setString(1, filename);/
            FileInputStream fis = new FileInputStream(file);
            prest.setBlob(2, fis,file.length());
            prest.execute();   //执行
            if(prest!=null){
                prest.close();
            }
            if(conn!=null){
                conn.close();
            }
    
        }
    

    接收方法,调用上一步插入图片插入成功

    /**
         * 新增文件
         */
        @PreAuthorize("@ss.hasPermi('system:bin:add')")
        @Log(title = "文件", businessType = BusinessType.INSERT)
        @PostMapping
        public AjaxResult add( @RequestParam("file") MultipartFile file) throws Exception {
            File toFile = null;
            if (file.equals("") || file.getSize() <= 0) {
                file = null;
            } else {
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }
            save(toFile);
            return toAjax(1);
        }
          //获取流文件
        private static void inputStreamToFile(InputStream ins, File file) {
            try {
                OutputStream os = new FileOutputStream(file);
                int bytesRead = 0;
                byte[] buffer = new byte[8192];
                while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
                os.close();
                ins.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    

    图片下载

    前台下载方法,传入文件名

     //文件下载
        downloadfile(){
          this.queryParams.filename=this.form.filename;
           const queryParams = this.queryParams;
    
      this.$confirm('是否确认下载?', "警告", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }).then(function() {
              return downloadBin(queryParams);
            }).then(response => {
              this.download(response.msg);
            }).catch(function() {});
     
        },
    

    后台下载方法

    
       /**
         * 下载文件
         */
        @GetMapping("/download")
        public AjaxResult download(TabBin tabBin) throws Exception {
            Connection conn = getConnection();
            System.out.print("1");
            String filename=tabBin.getFilename();
            String sql = "select * from tab_bin where filename= '"+filename+"'";
            PreparedStatement prest = conn.prepareStatement(sql);
    
            ResultSet rs = prest.executeQuery();
            OutputStream out = null;
            while(rs.next()){
                Blob bl = rs.getBlob("data"); 
                InputStream is = bl.getBinaryStream();  //查看blob,可以通过流的形式取出来。
                BufferedInputStream buffis = new BufferedInputStream(is);
                //保存到buffout,就工程目录下的filename的文件
    
                BufferedOutputStream buffout = new BufferedOutputStream( new FileOutputStream(getAbsoluteFile(filename)));
                byte[] buf= new byte[1024];
                int len = buffis.read(buf, 0, 1024);
                while(len>0){
                    buffout.write(buf);
                    len=buffis.read(buf, 0, 1024);
                }
                buffout.flush();
                buffout.close();
                buffis.close();
            }
            if(prest!=null){
                prest.close();
            }
            if(conn!=null){
                conn.close();
            }
            return AjaxResult.success(filename);
        }
    

    图片预览

    前台打开修改界面时,提前调用查询图片方法,传入文件名

    /** 修改按钮操作 */
        handleUpdate(row) {
          this.reset();
          const id = row.id || this.ids
          getBin(id).then(response => {
            this.form = response.data;
            this.open = true;
            this.title = "修改文件";
    
    
    
            this.queryParams.filename=this.form.filename;
            const queryParams = this.queryParams;
            updownload(queryParams).then(response => {
            console.log(response);
            //增加判断
            if(this.queryParams.filename.indexOf(".png") != -1){
              this.form.data='data:image/png;base64,'+response.msg;
            }else if(this.queryParams.filename.indexOf(".jpg") != -1){
              this.form.data='data:image/jpg;base64,'+response.msg;
            }
           
            })
           
    
          });
        },
    

    后台返回转好的base64码,注意图片格式。这里我只用了png和jpg

    @GetMapping("/updownload")
        public AjaxResult updownload(TabBin tabBin) throws Exception {
            Connection conn = getConnection();
            System.out.print("1");
            String filename=tabBin.getFilename();
            String sql = "select * from tab_bin where filename= '"+filename+"'";
            PreparedStatement prest = conn.prepareStatement(sql);
    
            ResultSet rs = prest.executeQuery();
            OutputStream out = null;
            String result="";
            while(rs.next()){
                Blob realBlob = rs.getBlob("data");
                // 创建byte数组输出对象
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                // 创建一个长度为100的byte数组
                byte[] buff = new byte[100];
                int rc = 0;
                // 获取BLOB数据对象的二进制流
                InputStream binaryStream = realBlob.getBinaryStream();
                while ((rc = binaryStream.read(buff, 0, 100)) > 0) {
                    byteArrayOutputStream.write(buff, 0, rc);
                }
                byte[] byteArray = byteArrayOutputStream.toByteArray();
                result = Base64.getEncoder().encodeToString(byteArray);
    
            }
            if(prest!=null){
                prest.close();
            }
            if(conn!=null){
                conn.close();
            }
            return AjaxResult.success(result);
        }
    

    前台显示,主要是img标签src绑定值替换为后台传过来的base64编码即可达成预览效果。

     <img :src="form.data" style="width:50%;height:50%"  >
    
    展开全文
  • 主要介绍了vue.js实现数据库的JSON数据输出渲染到html页面功能,结合实例形式分析了vue.js针对本地json数据的读取、遍历输出相关操作技巧,需要的朋友可以参考下
  • 在使用spring boot做后台系统,vue做前端系统,给客户开发一套系统时候,其中用到了图片上传和显示的功能。 二、环境 前端:vue 前端组件:tinymce 后台:spring boot:2.2.3 三、正文 在客户开发一套门户管理...
  • 主要介绍了vue+node实现图片上传及预览的示例方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
  • //上传图片 @RequestMapping("/upload") @ResponseBody public Map<String, Object> uploadToUser(@RequestParam("file") MultipartFile file) { Map<String, Object> map = new HashMap<>()...
       //后端代码
        //上传图片
        @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 +
                    '}';
        }
    }
    
    
    展开全文
  • springboot+vue实现增(包含上传图片)删改查打包到服务器并同时插入数据库 *hello everybody,为了让大家更快的找到自己想要的功能,我们先来看看需要完成的项目是什么样子的叭 如下: 那我们再来看看做出来的效果图...

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

    *hello everybody,为了让大家更快的找到自己想要的功能,我们先来看看需要完成的项目是什么样子的叭
    如下:
    在这里插入图片描述

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

    在这里插入图片描述

    新增以后显示的效果:

    在这里插入图片描述
    大家可以看出,我刚刚上传的图片是可以显示的,新增的数据也是有的(如果图片显示不出来刷新一下即可),至于修改跟删除是一样的啦,只是修改会根据你的id获取你的数据显示在form表单上,这个下面我们会提的,删除等会咱也会提的哈,8要着急

    在这里插入图片描述

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

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

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

    接下来,贴一我的数据库

    第一个是goods表:

    在这里插入图片描述

    第二个是GoodsDetail表:

    在这里插入图片描述

    ok,next,我们来写后台代码吼。。。。。。。。。。。。。。。。。。。。。。。。。。在这里插入图片描述

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

    在这里插入图片描述

    我先把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>
    
    

    好了,后台代码到这里就结束了,咱们进入前端哈。。。。。。。。。。。。。在这里插入图片描述

    前端我们用的是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,他自己就会打包

    在这里插入图片描述


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

    在这里插入图片描述

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

    ok,fine,今天的代码到这里已经全部分享完了,如果有问题私信我,也欢迎指正啦,啾咪。在这里插入图片描述

    展开全文
  • 前端页面,使用vant的uploader图片上传 < p style = "clear:both;text-align: left;margin:0px 0px 0px 10px ;color: #999999;padding: 0;" > 图片信息:(最多 10 张) < / p > < van - uploader v - model ...
  • 实现图片上传的方法有很多,这里我们介绍比较简单的一种,使用base64对图片信息进行编码,然后直接将图片的base64信息存到数据库。 但是对于系统中需要上传图片较多时并不建议采用这种方式,我们一般会选择存图片...
  • html内容: <el-row> <el-col :span="3" :offset="1"> 图片跳转链接 </el-col> <el-col :span="6"> <el-input v-model="imgLink" > ...
  • vue上传图片至项目resource文件夹,将路径返回至前端,并将路径保存在数据库; 前端代码: <el-form-itemlabel="商品图片:":sm="3"prop="pic"> <el-col:sm="16"> <el-uploadclass="upload-...
  • 前端使用vue 使用iview 中的upload上传组件 后端使用spring boot 中的 MultipartFile+ ftp 将图片上传到服务器 pom.xml 导入相应jar包 <dependencies> <dependency> <groupId>org....
  • Vue.js从数据库图片

    千次阅读 2019-03-19 21:18:52
    Vue.js从数据库图片 要求:将表中的内容(图片、文字)在页面渲染出来 表内容: 最终效果: VUE 数据库 1-1:HTML PS:[item.”表:字段名”] <!-- 主体图片/文字开始 --> <div class="content_...
  • asp.net mvc 上传图片数据库
  • 今天小编就为大家分享一篇vue中使用axios post上传头像/图片并实时显示到页面的方法,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
  • 主要为大家详细介绍了vue+element-ui+axios实现图片上传,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • 主要介绍了SpringBoot+Vue.js实现前后端分离的文件上传功能,需要的朋友可以参考下
  • vue数据库获取数据显示到页面下拉框里面;目前有后端的查询所有数据的端口,求源码。![图片说明](https://img-ask.csdn.net/upload/201912/11/1576032653_665124.png)
  • *最近有个需求就是在对文件(.txt)进行查库操作,文件里面的数组有一定的...在前端用elment的upload组件进行上传。 <template> <el-upload class="upload-demo" action="/export" :on-preview="handl...
  • 这是从后台数据库传输过来的图片路径 这是axios接收后台数据的代码 这是F12里面的图片路径 然后显示是这样的 这是我显示的代码 我之前使用require对代码部分进行了修改,也就是 把 :src=“like.gImage” 改成了 :src...
  • 1.首先在数据库一张表中建立存储文件二进制数据的字段 对于BLOB 类型的定义: 一个 BLOB 是一个可以保存一可变数量的数据的二进制大对象。另外还有三个兄弟类型(TINYBLOB、MEDIUMBLOB 和 LONGBLOB)它们之间的...
  • 使用Spring Boot上传文件的简单Demo
  • //上面的代码是一个form表单,model为ruleForm,这里我将element图片上传组件写在表单提交按钮的上面,在点击提交表单按钮时同时将图片传给后台,主要是将图片上传,表单代码就省略了 <div class="up...
  • 数据库我使用的是MongoDB。 首先做文件上传,要保证协议里面的’Content-Type’为’multipart/form-data’。...前端框架使用的是vue.js,ajax使用的是vue的组件vue-resource。 前端上传代码如下: <!--
  • 我们要是学的不够好,就比如我想在数据库里面传入一段网址当做图片呗,如下: 网址怎么拿的?CSDN啊,写博客的时候都有的,大家注意一下呗 使用技术前后端分离(SpringBoot+Vue) 那么后端就之间传一段网址过来撒...
  • :limit="1" 最多上传文件数 list-type="picture" 上传文件类型 action="" 上传地址 auto-upload 是否自动上传 on-change 事件获取文件信息 <template> <div class="PersonalData" > <div ...
  • 我们在写后台管理系统的时候,有时候需要上传图片,那么就要用到upload组件,刚好最近写项目遇到,记录一下 效果展示 点击按钮然后选择电脑里的图片,下面列表会进行图片的预览展示,提交表单便会提交图片的信息...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 13,844
精华内容 5,537
关键字:

vue如何上传图片进数据库

vue 订阅