非常简单实用的前后端分离项目-仓库管理系统(Springboot+Vue)part 5(未实现预期目标)

进行文件功能的书写,依旧新建查询。

CREATE TABLE `goods_file` (
    `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
    `goods_id` INT(11) NOT NULL COMMENT '物品ID,关联goods表',
    `file_name` VARCHAR(255) NOT NULL COMMENT '文件名',
    `file_path` VARCHAR(255) NOT NULL COMMENT '文件路径(相对于loadfile目录)',
    `file_size` BIGINT(20) DEFAULT NULL COMMENT '文件大小(字节)',
    `upload_time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '上传时间',
    PRIMARY KEY (`id`),
    FOREIGN KEY (`goods_id`) REFERENCES `goods`(`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='对应文件表';

在代码生成器中,完成代码的生成

在wms和wms-web同级下加一个文件夹goodsfile用于存储文件。完善生成的六个代码
 

package com.wms.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.time.LocalDateTime;
import java.io.Serializable;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;

/**
 * <p>
 * 对应文件表
 * </p>
 *
 * @author wms
 * @since 2024-12-24
 */
@Data
@EqualsAndHashCode(callSuper = false)
@ApiModel(value="GoodsFile对象", description="对应文件表")
public class GoodsFile implements Serializable {

    private static final long serialVersionUID = 1L;

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

    @ApiModelProperty(value = "物品ID,关联goods表")
    private Integer goodsId;

    @ApiModelProperty(value = "文件名")
    private String fileName;

    @ApiModelProperty(value = "文件路径(相对于loadfile目录)")
    private String filePath;

    @ApiModelProperty(value = "文件大小(字节)")
    private Long fileSize;

    @ApiModelProperty(value = "上传时间")
    private LocalDateTime uploadTime;



    /*@TableField(exist = false)
    private String url; // 用于前端显示下载链接*/
}
package com.wms.mapper;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.wms.entity.GoodsFile;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.wms.entity.Goodstype;
import org.apache.ibatis.annotations.Param;

/**
 * <p>
 * 对应文件表 Mapper 接口
 * </p>
 *
 * @author wms
 * @since 2024-12-24
 */
public interface GoodsFileMapper extends BaseMapper<GoodsFile> {
    IPage pageCC(IPage<GoodsFile> page, @Param(Constants.WRAPPER) Wrapper wrapper);
}
package com.wms.service.impl;

import com.wms.entity.GoodsFile;
import com.wms.mapper.GoodsFileMapper;
import com.wms.service.GoodsFileService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 对应文件表 服务实现类
 * </p>
 *
 * @author wms
 * @since 2024-12-24
 */
@Service
public class GoodsFileServiceImpl extends ServiceImpl<GoodsFileMapper, GoodsFile> implements GoodsFileService {

}
package com.wms.service;

import com.wms.entity.GoodsFile;
import com.baomidou.mybatisplus.extension.service.IService;
import org.springframework.web.multipart.MultipartFile;

/**
 * <p>
 * 对应文件表 服务类
 * </p>
 *
 * @author wms
 * @since 2024-12-24
 */
public interface GoodsFileService extends IService<GoodsFile> {

}
<?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.wms.mapper.GoodsFileMapper">
    <select id="pageCC" resultType="com.wms.entity.GoodsFile">
        select * from goods_file ${ew.customSqlSegment}
    </select>
    <!-- 通用查询映射结果 -->
    <resultMap id="BaseResultMap" type="com.wms.entity.GoodsFile">
        <id column="id" property="id" />
        <result column="goods_id" property="goodsId" />
        <result column="file_name" property="fileName" />
        <result column="file_path" property="filePath" />
        <result column="file_size" property="fileSize" />
        <result column="upload_time" property="uploadTime" />
    </resultMap>

    <sql id="Base_Column_List">
        id, goods_id, file_name, file_path, file_size, upload_time
    </sql>

</mapper>
package com.wms.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wms.common.QueryPageParam;
import com.wms.common.Result;
import com.wms.entity.Goods;
import com.wms.entity.GoodsFile;
import com.wms.entity.Storage;
import com.wms.service.GoodsFileService;
import com.wms.service.GoodsService;
import com.wms.service.StorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wms
 * @since 2024-12-07
 */
@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodsFileService goodsFileService; // 注入 GoodsFileService
    //新增
    @PostMapping("/save")
    public Result save(@RequestBody Goods goods) {
        return goodsService.save(goods)?Result.success():Result.fail();
    }
    //更新
    @PostMapping("/update")
    public Result update(@RequestBody Goods goods) {
        return goodsService.updateById(goods)?Result.success():Result.fail();
    }
    @GetMapping("/del")
    public Result del(@RequestParam String id) {
        return goodsService.removeById(id)?Result.success():Result.fail();
    }

    @PostMapping("/listPage")
    public Result listPage(@RequestBody QueryPageParam query) {
        HashMap param = query.getParam();
        String name = (String) param.get("name");
        String storage = (String) param.get("storage");
        String goodstype = (String) param.get("goodstype");

        Page<Goods> page = new Page();
        page.setCurrent(query.getPageNum());
        page.setSize(query.getPageSize());

        LambdaQueryWrapper<Goods> lambdaQueryWrapper = new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(name)&&!"null".equals(name)) {
            lambdaQueryWrapper.like(Goods::getName, name);
        }
        if(StringUtils.isNotBlank(storage)&&!"null".equals(storage)) {
            lambdaQueryWrapper.eq(Goods::getStorage, storage);
        }
        if(StringUtils.isNotBlank(goodstype)&&!"null".equals(goodstype)) {
            lambdaQueryWrapper.eq(Goods::getGoodstype, goodstype);
        }

        IPage result=goodsService.pageCC(page,lambdaQueryWrapper);
        return Result.success(result.getRecords(),result.getTotal());
    }
    @GetMapping("/list")
    public Result list(QueryPageParam query) {
        Page<Goods> page = new Page<>(query.getPageNum(), query.getPageSize());
        QueryWrapper<Goods> queryWrapper = new QueryWrapper<>();
        if (!"".equals(query.getParam()) && query.getParam() != null) {
            queryWrapper.like("name", query.getParam());
        }
        IPage<Goods> result = goodsService.pageCC(page, queryWrapper);

        //  获取每个物品的文件信息
        List<Goods> records = result.getRecords();
        records.forEach(goods -> {
            QueryWrapper<GoodsFile> fileQueryWrapper = new QueryWrapper<>();
            fileQueryWrapper.eq("goods_id", goods.getId());
            GoodsFile goodsFile = goodsFileService.getOne(fileQueryWrapper);
            goods.setFileInfo(goodsFile); //  假设你在 Goods 实体类中添加了 fileInfo 属性
        });

        HashMap<String, Object> data = new HashMap<>();
        data.put("records", records);
        data.put("total", result.getTotal());
        return Result.success(data);
    }


}
package com.wms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wms.common.Result;
import com.wms.entity.GoodsFile;
import com.wms.service.GoodsFileService;
import com.wms.service.GoodsService;
import org.apache.tomcat.jni.FileInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/file")
public class GoodsFileController {
    @Value("${file.upload.path}")
    private String uploadBasePath;

    @Autowired
    private ResourceLoader resourceLoader;

    @Autowired
    private GoodsFileService goodsFileService; // 服务名称改为与实体对应

    @PostMapping("/upload")
    public Result uploadGoodsFile(@RequestParam("file") MultipartFile file, @RequestParam("goodsId") Integer goodsId) {
        try {
            // 检查是否已存在该商品的文件
            QueryWrapper<GoodsFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_id", goodsId);
            GoodsFile existingFile = goodsFileService.getOne(queryWrapper);
            if (existingFile != null) {
                // 删除旧文件
                Resource resource = resourceLoader.getResource(uploadBasePath);
                File oldFile = new File(resource.getFile().getAbsolutePath() + "/" + existingFile.getFilePath());
                if (oldFile.exists()) {
                    oldFile.delete();
                }
                goodsFileService.remove(queryWrapper);
            }

            // 获取文件名
            String originalFilename = file.getOriginalFilename();
            // 生成新的文件名
            String fileName = UUID.randomUUID().toString() +
                    originalFilename.substring(originalFilename.lastIndexOf("."));

            // 获取资源路径
            File uploadDir = new File(uploadBasePath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            Path path = Paths.get(uploadDir.getAbsolutePath() + "/" + fileName);
            Files.write(path, file.getBytes());



            // 保存文件信息到数据库
            GoodsFile goodsFile = new GoodsFile(); // 实体类改名为 GoodsFile
            goodsFile.setGoodsId(goodsId);
            goodsFile.setFileName(originalFilename);
            goodsFile.setFilePath(fileName);
            goodsFile.setFileSize(file.getSize());
            goodsFileService.save(goodsFile);

            return Result.success();
        } catch (IOException e) {
            e.printStackTrace();
            return Result.fail();
        }
    }

    @GetMapping("/download/{goodsId}")
    public ResponseEntity<Resource> downloadGoodsFile(@PathVariable Integer goodsId) {
        try {
            // 查询文件信息
            QueryWrapper<GoodsFile> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("goods_id", goodsId);
            GoodsFile goodsFile = goodsFileService.getOne(queryWrapper);
            if (goodsFile == null) {
                return ResponseEntity.notFound().build();
            }

            // 获取文件
            Resource resource = resourceLoader.getResource("file:" + uploadBasePath + goodsFile.getFilePath());

            // 设置响应头
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .header(HttpHeaders.CONTENT_DISPOSITION,
                            "attachment; filename=\"" + URLEncoder.encode(goodsFile.getFileName(), "UTF-8") + "\"")
                    .body(resource);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/info/{goodsId}")
    public Result getGoodsFileInfo(@PathVariable Integer goodsId) {
        QueryWrapper<GoodsFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", goodsId);
        GoodsFile goodsFile = goodsFileService.getOne(queryWrapper);
        return Result.success(goodsFile);
    }
}

在GoodsManage.vue中添加此功能 (前端暂未完善,会报错)

<template>
  <div>
    <div style="margin-left:5px;">
      <el-input v-model="name" placeholder="请输入物品名:" suffix-icon="el-icon-search" style="width:200px;"
                @keyup.enter.native="loadPost"></el-input>
      <el-select v-model="storage" placeholder="请选择仓库" style="margin-left: 5px;">
        <el-option
            v-for="item in storageData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>
      <el-select v-model="goodstype" placeholder="请选择分类" style="margin-left: 5px;">
        <el-option
            v-for="item in goodstypeData"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
      </el-select>

      <el-button type="primary" style="margin-left:5px" @click="loadPost">查询</el-button>
      <el-button type="success" @click="resetParam">重置</el-button>
      <el-button type="primary" style="margin-left:5px" @click="add" v-if="user.roleId!=2">新增</el-button>
      <el-button type="success" style="margin-left:5px;" @click="inGoods" v-if="user.roleId!=2">入库</el-button>
      <el-button type="success" style="margin-left:5px;" @click="outGoods" v-if="user.roleId!=2">出库</el-button>
    </div>
    <el-table :data="tableData"
              :header-cell-style="{background:'#f2f5fc',color:'#555'}"
              border
              highlight-current-row
              @current-change="selectCurrentChange"
    >
      <el-table-column prop="id" label="ID" width="60">
      </el-table-column>
      <el-table-column prop="name" label="物品名" width="80">
      </el-table-column>
      <el-table-column prop="storage" label="仓库" :formatter="formatStorage">
      </el-table-column>
      <el-table-column prop="goodstype" label="分类" :formatter="formatGoodsType">
      </el-table-column>
      <el-table-column prop="count" label="数量">
      </el-table-column>
      <el-table-column prop="remark" label="备注">
      </el-table-column>
      <el-table-column prop="operate" label="操作" v-if="user.roleId!=2">
        <template slot-scope="scope">
          <el-button size="small" type="success" @click="mod(scope.row)">编辑</el-button>
          <el-popconfirm
              title="确定删除吗?"
              @confirm="del(scope.row.id)"
              style="margin-left:8px;"
          >
            <el-button slot="reference" size="small" type="danger">删除</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[5, 10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
    <el-dialog
        title="物品维护"
        :visible.sync="centerDialogVisible"
        width="30%"
        center>

      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="物品名" prop="name">
          <el-col :span="20">
            <el-input v-model="form.name"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="仓库" prop="storage">
          <el-col :span="20">
            <el-select v-model="form.storage" placeholder="请选择仓库" style="margin-left: 5px;">
              <el-option
                  v-for="item in storageData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="分类" prop="goodstype">
          <el-col :span="20">
            <el-select v-model="form.goodstype" placeholder="请选择分类" style="margin-left: 5px;">
              <el-option
                  v-for="item in goodstypeData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-col :span="20">
            <el-input v-model="form.count"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="20">
            <el-input type="textarea" v-model="form.remark"></el-input>
          </el-col>
        </el-form-item>

        <el-table-column label="附件">
          <template slot-scope="scope">
            <el-button
                v-if="scope.row.fileInfo && scope.row.fileInfo.fileName"
                type="text"
                size="small"
                @click="downloadFileFromList(scope.row.fileInfo.goodsId)"
            >{{ scope.row.fileInfo.fileName }}</el-button>
            <span v-else>无</span>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>



        <el-form-item label="附件">
          <el-upload
              class="upload-demo"
              ref="upload"
              :action="'http://localhost:8090/file/upload'"
              :on-success="handleFileUploadSuccess"
              :on-error="handleFileUploadError"
              :auto-upload="true"
              :file-list="fileList"
              :data="{ goodsId: form.id }"
              :limit="1"
              :before-upload="beforeFileUpload"
          >
          <el-button size="small" type="primary">点击上传</el-button>
            <a href="https://dl-pc-sz-cf.pds.quark.cn/RVZcMSAW/7701856490/676cf6fa53e0d58830e945b1beeb223874537c8b/676cf6fa4a789dd5ee4847ab97a7bb17507f83f8?Expires=1735216840&OSSAccessKeyId=LTAI5tJJpWQEfrcKHnd1LqsZ&Signature=%2BRa5TQd3QBjECPsYo%2B23f9DT%2F6o%3D&x-oss-traffic-limit=503316480&response-content-disposition=attachment%3B%20filename%3Dtest.txt%3Bfilename%2A%3Dutf-8%27%27test.txt&callback-var=eyJ4OmF1IjoiLSIsIng6dWQiOiIxNi0wLTQtMC00LU4tNC1OLTEtMTYtMC1OIiwieDpzcCI6IjEwMCIsIng6dG9rZW4iOiI0LTE5NWQxM2Y5YzIzZWY4NzUxOTlkZTg5ZjQ0ODA3ZDg2LTItMS0xMDI0LTI5MDQ0YWQyMjMxZDRmNDU4MmI1ZWQwNzU2YmQ2Yjc3LTAtMC0wLTAtM2VmZjZkMDU2OTQ0OGQzNDM1ZjhiMzQ1Y2E5YjMwZmYiLCJ4OnR0bCI6IjIxNjAwIn0%3D&abt=2_0_&callback=eyJjYWxsYmFja0JvZHlUeXBlIjoiYXBwbGljYXRpb24vanNvbiIsImNhbGxiYWNrU3RhZ2UiOiJiZWZvcmUtZXhlY3V0ZSIsImNhbGxiYWNrRmFpbHVyZUFjdGlvbiI6Imlnbm9yZSIsImNhbGxiYWNrVXJsIjoiaHR0cHM6Ly9jbG91ZC1hdXRoLmRyaXZlLnF1YXJrLmNuL291dGVyL29zcy9jaGVja3BsYXkiLCJjYWxsYmFja0JvZHkiOiJ7XCJob3N0XCI6JHtodHRwSGVhZGVyLmhvc3R9LFwic2l6ZVwiOiR7c2l6ZX0sXCJyYW5nZVwiOiR7aHR0cEhlYWRlci5yYW5nZX0sXCJyZWZlcmVyXCI6JHtodHRwSGVhZGVyLnJlZmVyZXJ9LFwiY29va2llXCI6JHtodHRwSGVhZGVyLmNvb2tpZX0sXCJtZXRob2RcIjoke2h0dHBIZWFkZXIubWV0aG9kfSxcImlwXCI6JHtjbGllbnRJcH0sXCJwb3J0XCI6JHtjbGllbnRQb3J0fSxcIm9iamVjdFwiOiR7b2JqZWN0fSxcInNwXCI6JHt4OnNwfSxcInVkXCI6JHt4OnVkfSxcInRva2VuXCI6JHt4OnRva2VufSxcImF1XCI6JHt4OmF1fSxcInR0bFwiOiR7eDp0dGx9LFwiZHRfc3BcIjoke3g6ZHRfc3B9LFwiaHNwXCI6JHt4OmhzcH0sXCJjbGllbnRfdG9rZW5cIjoke3F1ZXJ5U3RyaW5nLmNsaWVudF90b2tlbn19In0%3D&ud=16-0-4-0-4-N-4-N-1-16-0-N" target="_blank">
              <el-button size= "small" type="success">点击下载</el-button>
            </a>
          <div slot="tip" class="el-upload__tip">只能上传不超过 5MB 的图片/PDF 文件</div>
          </el-upload>
        </el-form-item>


        <el-form-item v-if="fileInfo && fileInfo.fileName" label="已上传附件">
          <span>{{ fileInfo.fileName }}</span>
          <el-button type="text" size="small" @click="downloadFile">下载</el-button>
        </el-form-item>




      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="save">确定</el-button>
  </span>
    </el-dialog>

    <el-dialog
        title="出入库"
        :visible.sync="inDialogVisible"
        width="30%"
        center>

      <el-dialog
          width="70%"
          title="用户选择"
          :visible.sync="innerVisible"
          append-to-body>
        <SelectUser @doSelectUser="doSelectUser"></SelectUser>
        <span slot="footer" class="dialog-footer">
        <el-button @click="innerVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmUser">确定</el-button>
        </span>
      </el-dialog>

      <el-form ref="form1" :rules="rules1" :model="form1" label-width="80px">
        <el-form-item label="物品名">
          <el-col :span="20">
            <el-input v-model="form1.goodsname" readonly></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="申请人">
          <el-col :span="20">
            <el-input v-model="form1.username" readonly @click.native="selectUser"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="数量" prop="count">
          <el-col :span="20">
            <el-input v-model="form1.count"></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-col :span="20">
            <el-input type="textarea" v-model="form1.remark"></el-input>
          </el-col>
        </el-form-item>

      </el-form>



      <span slot="footer" class="dialog-footer">
        <el-button @click="inDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="doInGoods">确定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<style scoped>

</style>
<script>

import SelectUser from "../user/SelectUser";

export default {
  name: "GoodsManage",
  components: {SelectUser},
  data() {
    let checkCount = (rule, value, callback) => {
      if (value > 9999) {
        callback(new Error('数量输入过大'));
      } else {
        callback();
      }
    };
    return {

      user: JSON.parse(sessionStorage.getItem('CurUser')),
      storageData: [],
      tableData: [],
      goodstypeData: [],
      pageSize: 10,
      pageNum: 1,
      storage: '',
      goodstype: '',

      fileList: [], // 用于 el-upload 显示已上传的文件列表
      fileInfo: null, // 用于存储从后端获取的文件信息

      total: 0,
      name: '',
      centerDialogVisible: false,
      inDialogVisible: false,
      innerVisible: false,
      currentRow: {},
      tempUser: {},
      form: {
        id: '',
        name: '',
        remark: '',
        count: '',
        storage: '',
        goodstype: '',
      },
      form1: {
        goods: '',
        goodsname: '',
        count: '',
        username: '',
        userid: '',
        adminId: '',
        remark: '',
        action: '1'
      },
      rules1: {},
      rules: {
        name: [
          {required: true, message: '请输入物品名', trigger: 'blur'},
        ],
        storage: [
          {required: true, message: '请选择仓库', trigger: 'blur'}
        ],
        goodstype: [
          {required: true, message: '请选择分类',trigger:'blur'}
        ],
        count: [
          {required: true, message: '请输入数量', trigger: 'blur'},
          {pattern: /^([1-9][0-9]*){1,4}$/, message: '数量必须为正整数', trigger: "blur"},
          {validator: checkCount, trigger: 'blur'}
        ]
      }
    }
  },
  methods: {
    confirmUser() {
      this.form1.username = this.tempUser.name
      this.form1.userid = this.tempUser.id
      this.innerVisible = false
    },
    doSelectUser(val) {
      console.log(val)
      this.tempUser = val
    },
    selectCurrentChange(val) {
      this.currentRow = val;
    },


    beforeFileUpload(file) {
      const isPdfOrImage = ['image/jpeg', 'image/png', 'application/pdf'].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!isPdfOrImage) {
        this.$message.error('上传文件只能是 JPG、PNG、 PDF格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }
      return isPdfOrImage && isLt5M;
    },
    handleFileUploadSuccess(response, file, fileList) {
      this.$message.success('文件上传成功');
      // 上传成功后,重新获取文件信息,更新文件名和下载按钮的显示
      this.getFileInfo(this.form.id);
    },
    handleFileUploadError(err) {
      this.$message.error('文件上传失败');
      console.error(err);
    },
    downloadFile() {
      if (this.fileInfo && this.fileInfo.goodsId) {
        window.open(`http://localhost:8090/file/download/${this.fileInfo.goodsId}`); //  替换为你的下载接口地址
      }
    },
    // 获取文件信息
    getFileInfo(goodsId) {
      this.$axios.get(`/file/info/${goodsId}`).then(res => {
        if (res.code === '200') {
          this.fileInfo = res.data;
        }
      });
    },
    downloadFileFromList(goodsId) {
      axios.get(`/file/info/${goodsId}`)
          .then(response => {
            // 处理文件下载逻辑
            const fileInfo = response.data;
            this.downloadFile(fileInfo);
          })
          .catch(error => {
            console.error('Error downloading file:', error);
            // 显示错误信息
            this.$message.error('下载文件失败');
          });//  替换为你的下载接口地址
    },

    formatStorage(row) {
      let temp = this.storageData.find(item => {
        return item.id == row.storage
      })
      return temp && temp.name
    },
    formatGoodsType(row) {
      let temp = this.goodstypeData.find(item => {
        return item.id === row.goodstype
      })
      return temp && temp.name
    },
    add() {
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.resetForm()
        this.form.id = ''
      })
    },
    inGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录');
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm()

      })
      this.form1.goodsname = this.currentRow.name
      this.form1.goods = this.currentRow.id
      this.form1.adminId = this.user.id
      this.form1.action = '1'
    },
    outGoods() {
      if (!this.currentRow.id) {
        alert('请选择记录');
        return;
      }
      this.inDialogVisible = true
      this.$nextTick(() => {
        this.resetInForm()
      })
      this.form1.goodsname = this.currentRow.name
      this.form1.goods = this.currentRow.id
      this.form1.adminId = this.user.id
      this.form1.action = '2'
    },
    mod(row) {
      //this.form=row就可以了
      this.centerDialogVisible = true
      this.$nextTick(() => {
        this.form.id = row.id;
        this.form.remark = row.remark;
        this.form.name = row.name;
        this.form.storage = row.storage;
        this.form.goodstype = row.goodstype;
        this.form.count = row.count;
        /**/
        this.form = { ...row }; // 使用 ... 展开运算符复制对象,避免直接引用
        this.getFileInfo(row.id); // 在打开编辑弹窗时获取文件信息
        /**/
      })
    },
    del(id) {
      this.$axios.get(this.$httpUrl + '/goods/del?id=' + id).then(res => res.data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: '操作成功!',
            type: 'success'
          });
          this.loadPost();
        } else {
          this.$message({
            message: '操作失败!请返回重新操作...',
            type: 'error'
          });
        }
      });
    },
    selectUser() {
      this.innerVisible = true;
    },
    resetForm() {
      //this.centerDialogVisible = true
      this.$refs.form.resetFields();
      //this.form.id = '';
    },
    resetInForm() {
      this.$refs.form1.resetFields();
    },
    doSave() {
      this.$axios.post(this.$httpUrl + '/goods/save', this.form).then(res => res.data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: '操作成功!',
            type: 'success'
          });
          this.centerDialogVisible = false
          this.loadPost()
          this.resetForm()
        } else {
          this.$message({
            message: '操作失败!请返回重新操作...',
            type: 'error'
          });
        }
      })
    },
    doMod() {
      this.$axios.post(this.$httpUrl + '/goods/update', this.form).then(res => res.data).then(res => {
        console.log(res)
        if (res.code == 200) {
          this.$message({
            message: '操作成功!',
            type: 'success'
          });
          this.centerDialogVisible = false;
          this.loadPost();
          this.resetForm();
        } else {
          this.$message({
            message: '操作失败!',
            type: 'error'
          });
        }
      });
    },
    save() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (this.form.id) {
            this.doMod();
          } else {
            this.doSave();
          }

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    loadPost() {
      this.$axios.post(this.$httpUrl + '/goods/listPage', {
        pageSize: this.pageSize,
        pageNum: this.pageNum,
        param: {
          name: this.name,
          goodstype: this.goodstype + '',//string和int强转一下
          storage: this.storage + ''
        }
      }).then(res => res.data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.tableData = res.data
          this.total = res.total
          // 将后端返回的 fileInfo 直接赋值给表格数据中的每一项
          this.tableData.forEach(item => {
            item.fileInfo = item.fileInfo || null; // 确保 fileInfo 存在,否则设置为 null
          });
        } else {
          alert('获取数据失败!请刷新页面')
        }
      })
    },
    loadStorage() {
      this.$axios.get(this.$httpUrl + '/storage/list').then(res => res.data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.storageData = res.data
        } else {
          alert('获取数据失败!请刷新页面')
        }
      })
    },
    loadGoodsType() {
      this.$axios.get(this.$httpUrl + '/goodstype/list').then(res => res.data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.goodstypeData = res.data
        } else {
          alert('获取数据失败!请刷新页面')
        }
      })
    },
    resetParam() {
      this.name = ''
      this.storage = ''
      this.goodstype = ''
    },
    doInGoods() {
      this.$axios.post(this.$httpUrl + '/record/save', this.form1).then(res => res.data).then(res => {
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: '操作成功!',
            type: 'success'
          });
          this.inDialogVisible = false
          this.loadPost();
          this.resetInForm()
        } else {
          this.$message({
            message: '操作失败!请返回重新操作...',
            type: 'error'
          });
        }
      });
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageNum = 1//这个错误是先翻到第二页在调页面条数,显示无数据
      this.pageSize = val
      this.loadPost()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pageNum = val
      this.loadPost()
    }
  },
  beforeMount() {
    this.loadStorage()
    this.loadGoodsType()
    this.loadPost()
  }
}

</script>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/946866.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

Unity2D无限地图的实现(简单好抄)

说明&#xff1a;本教程实现的是在2D游戏中玩家在游戏中上下左右移动的时候自动进行地图拼接的功能&#xff0c;如果你只想实现左右移动的无限地图&#xff0c;那么这篇博客也能起到一定参考作用。 思路 第一步&#xff1a; 创建一个10*10的2D游戏对象当做地图 第二步创建一个…

艾体宝方案丨全面提升API安全:AccuKnox 接口漏洞预防与修复

一、API 安全&#xff1a;现代企业的必修课 在现代技术生态中&#xff0c;应用程序编程接口&#xff08;API&#xff09;扮演着不可或缺的角色。从数据共享到跨平台集成&#xff0c;API 成为连接企业系统与外部服务的桥梁。然而&#xff0c;伴随云计算的普及与微服务架构的流行…

日期时间选择(设置禁用状态)

目录 1.element文档需要 2.禁用所有过去的时间 3.设置指定日期的禁用时间 <template><div class"block"><span class"demonstration">起始日期时刻为 12:00:00</span><el-date-pickerv-model"value1"type"dat…

SAP学习笔记 - 豆知识14 - Msg 番号 M7562 - 取引Type WL 对应的番号範囲中不存在2025年度 OMBT

这种类似的以前也写过&#xff0c;原因就是自动採番的番号没弄。 比如跨年了&#xff0c;那该新年度的番号范围没弄啊&#xff0c;就会出这种错误。 把番号范围给加一下就可以了。 1&#xff0c;现象 比如点 VL02N 出荷传票变更 画面&#xff0c;点 出库确认 就会出如下错误…

SpringBoot 集成 Activiti 7 工作流引擎

一. 版本信息 IntelliJ IDEA 2023.3.6JDK 17Activiti 7 二. IDEA依赖插件安装 安装BPM流程图插件&#xff0c;如果IDEA的版本超过2020,则不支持actiBPM插件。我的IDEA是2023版本我装的是 Activiti BPMN visualizer 插件。 在Plugins 搜索 Activiti BPMN visualizer 安装 创…

分布式版本管理工具——Git关联远程仓库(github+gitee)

Git远程仓库&#xff08;Github&#xff09;的基本使用 一、前言二、Git远程仓库介绍三、演示1. 关联github远程仓库2. 关联gitee&#xff08;码云&#xff09;远程仓库3. 重命名远程仓库名4. 移除远程仓库 四、结束语 一、前言 古之立大事者&#xff0c;不惟有超世之才&#x…

python-leetcode-删除有序数组中的重复项 II

80. 删除有序数组中的重复项 II - 力扣&#xff08;LeetCode&#xff09; class Solution:def removeDuplicates(self, nums: List[int]) -> int:n len(nums)if n < 2:return n # 如果长度小于等于 2&#xff0c;直接返回长度k 2 # 指针 k 指向下一个有效位置&#x…

欧科云链OKLink:比特币与以太坊“双重启动”将如何撬动市场?

近日&#xff0c;OKLink 与 137Labs 联合举办 X Space&#xff0c;围绕宏观经济环境、政策及机构投资的影响等话题&#xff0c;分享如何把握 Web3 中的潜在机会与辨别风险。OKG Research 首席研究员 Hedy、BuilderRocket Accelerator 研究合伙人 Vivienna、VC 分析员 Bunny、BU…

【Linux】Socket编程-UDP构建自己的C++服务器

&#x1f308; 个人主页&#xff1a;Zfox_ &#x1f525; 系列专栏&#xff1a;Linux 目录 一&#xff1a;&#x1f525; UDP 网络编程 &#x1f98b; 接口讲解&#x1f98b; V1 版本 - echo server&#x1f98b; V2 版本 - DictServer&#x1f98b; V3 版本 - 简单聊天室 二&a…

创建型设计模式、结构型设计模式与行为型设计模式 上下文任务通用方案 设计模式 大全

设计模式&#xff08;Design Pattern&#xff09;是一种面向对象编程思想&#xff0c;分为创建型模式、结构型模式与行为型模式三大类&#xff0c;提供在特定上下文中解决常见任务通用方案&#xff0c;旨在让程序&#xff08;软件&#xff09;具有更好特点&#xff0c;如降低耦…

如何查看下载到本地的大模型的具体大小?占了多少存储空间:Llama-3.1-8B下载到本地大概15GB

这里介绍一下tree命令&#xff0c;可以方便的查看文件目录结构和文件大小。 命令行tree的具体使用&#xff0c;请参考笔者的另一篇博客&#xff1a;深入了解 Linux tree 命令及其常用选项&#xff1a;Linux如何显示目录结构和文件大小&#xff0c;一言以蔽之&#xff0c;sudo a…

MySQL线上事故:使用`WHERE`条件`!=xxx`无法查询到NULL数据

前言 在一次 MySQL 的线上查询操作中&#xff0c;因为 ! 的特性导致未能正确查询到为 NULL 的数据&#xff0c;险些引发严重后果。本文将详细解析 NULL 在 SQL 中的行为&#xff0c;如何避免类似问题&#xff0c;并提供实际操作建议。 1. 为什么NULL会查询不到&#xff1f; 在…

4G报警器WT2003H-16S低功耗语音芯片方案开发-实时音频上传

一、引言 在当今社会&#xff0c;安全问题始终是人们关注的重中之重。无论是家庭、企业还是公共场所&#xff0c;都需要一套可靠的安全防护系统来保障人员和财产的安全。随着科技的飞速发展&#xff0c;4G 报警器应运而生&#xff0c;为安全防范领域带来了全新的解决方案。…

U盘格式化工具合集:6个免费的U盘格式化工具

在日常使用中&#xff0c;U盘可能会因为文件系统不兼容、数据损坏或使用需求发生改变而需要进行格式化。一个合适的格式化工具不仅可以清理存储空间&#xff0c;还能解决部分存储问题。本文为大家精选了6款免费的U盘格式化工具&#xff0c;并详细介绍它们的功能、使用方法、优缺…

玩转OCR | 腾讯云智能结构化OCR初次体验

目录 一、什么是OCR&#xff08;需要了解&#xff09; 二、产品概述与核心优势 产品概述 智能结构化能做什么 举例说明&#xff08;选看&#xff09; 1、物流单据识别 2、常见证件识别 3、票据单据识别 4、行业材料识别 三、产品特性 高精度 泛化性 易用性 四、…

基于微信小程序的校园自助打印系统

博主介绍&#xff1a;java高级开发&#xff0c;从事互联网行业六年&#xff0c;熟悉各种主流语言&#xff0c;精通java、python、php、爬虫、web开发&#xff0c;已经做了多年的设计程序开发&#xff0c;开发过上千套设计程序&#xff0c;没有什么华丽的语言&#xff0c;只有实…

driftingblues6_vh靶机

首先把靶机换成NAT模式 使用 arp-scan 命令扫描网段内存活的主机&#xff0c;以获取靶机ip地址 arp-scn -l 尝试访问ip 使用御剑扫描子域名&#xff0c;尝试访问robots.txt文件 通过访问文件我们发现了一个/textpattern/textpattern目录 访问一下目录发现了登录页面 他还给了…

STM32使用UART发送字符串与printf输出重定向

首先我们先看STM32F103C8T6的电路图 由图可知&#xff0c;其PA9和PA10引脚分别为UART的TX和RX(注意&#xff1a;这个电路图是错误的&#xff0c;应该是PA9是X而PA9是RX&#xff0c;我们看下图的官方文件可以看出)&#xff0c;那么接下来我们应该找到该引脚的定义是什么&#xf…

数据库自增 id 过大导致前端时数据丢失

可以看到&#xff0c;前端响应参数是没有丢失精度的 但是在接受 axios 请求参数时出现了精度丢失 解决方案一&#xff1a;改变 axios 字符编码 axios.defaults.headers[Content-Type] application/json;charsetUTF-8; 未解决 解决方案二&#xff1a;手动使用 json.parse() …

SpringBoot教程(三十二) SpringBoot集成Skywalking链路跟踪

SpringBoot教程&#xff08;三十二&#xff09; | SpringBoot集成Skywalking链路跟踪 一、Skywalking是什么&#xff1f;二、Skywalking与JDK版本的对应关系三、Skywalking下载四、Skywalking 数据存储五、Skywalking 的启动六、部署探针 前提&#xff1a; Agents 8.9.0 放入 …