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

news2024/12/28 7:37:40

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

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>

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

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

USB 状态机及状态转换

文章目录 USB 状态机及状态转换连接状态供电状态默认状态地址状态配置状态挂起状态USB 状态机及状态转换 枚举完成之前,USB 设备要经过一系列的状态变化,才能最终完成枚举。这些状态是 连接状态 - attached供电状态 - powered默认状态 - default地址状态 - address配置状态 -…

QT线程 QtConcurrent (深入理解)

QT多线程专栏共有16篇文章,从初识线程到、QMutex锁、QSemaphore信号量、Emit、Sgnals、Slot主线程子线程互相传值同步变量、QWaitCondition、事件循环、QObjects、线程安全、线程同步、线程异步、QThreadPool线程池、ObjectThread多线程操作、 moveToThread等线程操作进行了全…

Linux-Ubuntu之串口通信

Linux-Ubuntu之串口通信 一&#xff0c;串口通信1.串口通信寄存器配置2.串口通信软件实现①手动波特率②自动波特率③主函数 二&#xff0c;printf和scanf实现串口的输入显示 一&#xff0c;串口通信 1.串口通信寄存器配置 串口通信利用接口是这个TTL&#xff0c;下载程序用的…

阿尔萨斯(JVisualVM)JVM监控工具

文章目录 前言阿尔萨斯(JVisualVM)JVM监控工具1. 阿尔萨斯的功能2. JVisualVM启动3. 使用 前言 如果您觉得有用的话&#xff0c;记得给博主点个赞&#xff0c;评论&#xff0c;收藏一键三连啊&#xff0c;写作不易啊^ _ ^。   而且听说点赞的人每天的运气都不会太差&#xff…

41 stack类与queue类

目录 一、简介 &#xff08;一&#xff09;stack类 &#xff08;二&#xff09;queue类 二、使用与模拟实现 &#xff08;一&#xff09;stack类 1、使用 2、OJ题 &#xff08;1&#xff09;最小栈 &#xff08;2&#xff09;栈的弹出压入序列 &#xff08;3&#xf…

wangEditor富文本插件在vue项目中使用和媒体上传的实现

wangEditor是前端一个比较流行的简洁易用&#xff0c;功能强大的前端富文本编辑器&#xff0c;支持 JS Vue React&#xff0c;提供了很多丰富的功能&#xff0c;下面手把手教你实现wangWditor富文本插件在vue项目中配置&#xff0c;保存、图片上传等功能。无脑ctrlc即可 基本功…

VMwareTools安装(ubuntu23)

1.打开VMware&#xff0c;菜单栏虚拟机->安装VMwareTools 2.点开光驱&#xff0c;把压缩包复制到桌面 3.解压 如何开启sudo权限&#xff1a; sudo passwd root 之后输入密码查看解压文件夹&#xff0c;执行vmware-install.pl文件 安装过程中碰见如下报错信息&#xff1a;…

jangow-01-1.0.1靶机

靶机 ip&#xff1a;192.168.152.155 把靶机的网络模式调成和攻击机kali一样的网络模式&#xff0c;我的kali是NAT模式, 在系统启动时(长按shift键)直到显示以下界面 ,我们选第二个&#xff0c;按回车。 继续选择第二个&#xff0c;这次按 e 进入编辑页面 接下来&#xff0c;…

C# GDI+数码管数字控件

调用方法 int zhi 15;private void button1_Click(object sender, EventArgs e){if (zhi > 19){zhi 0;}lcdDisplayControl1.DisplayText zhi.ToString();} 运行效果 控件代码 using System; using System.Collections.Generic; using System.Drawing.Drawing2D; using …

Cilium:BPF 和 XDP 参考指南(2021)

大家觉得有意义和帮助记得及时关注和点赞!!! BPF 是 Linux 内核中一个非常灵活与高效的类虚拟机&#xff08;virtual machine-like&#xff09;组件&#xff0c; 能够在许多内核 hook 点安全地执行字节码&#xff08;bytecode &#xff09;。很多 内核子系统都已经使用了 BPF&a…

LabVIEW条件配置对话框

条件配置对话框&#xff08;Configure Condition Dialog Box&#xff09; 要求&#xff1a;Base Development System 当右键单击**条件禁用结构&#xff08;Conditional Disable Structure&#xff09;**并选择以下选项时&#xff0c;会显示此对话框&#xff1a; Add Subdiagr…

机器学习-高斯混合模型

文章目录 高斯混合模型对无标签的数据集&#xff1a;使用高斯混合模型进行聚类对有标签的数据集&#xff1a;使用高斯混合模型进行分类总结 高斯混合模型 对无标签的数据集&#xff1a;使用高斯混合模型进行聚类 对有标签的数据集&#xff1a;使用高斯混合模型进行分类 总结

GitLab 服务变更提醒:中国大陆、澳门和香港用户停止提供服务(GitLab 服务停止)

目录 前言 一. 变更详情 1. 停止服务区域 2. 邮件通知 3. 新的服务提供商 4. 关键日期 5. 行动建议 二. 迁移指南 三. 注意事项 四. 相关推荐 前言 近期&#xff0c;许多位于中国大陆、澳门和香港的 GitLab 用户收到了一封来自 GitLab 官方的重要通知。根据这封邮件…

MacOS下TestHubo安装配置指南

TestHubo是一款开源免费的测试管理工具&#xff0c; 下面介绍MacOS私有部署的安装与配置。TestHubo 私有部署版本更适合有严格数据安全要求的企业&#xff0c;支持在本地或专属服务器上运行&#xff0c;以实现对数据和系统的完全控制。 1、Mac 服务端安装 Mac安装包下载地址&a…

css绘制圆并绘制圆的半径

<div class"item1"></div>.item1 {position: relative;width: 420px;height: 420px;border-radius: 50%; /* 圆形 */color: white; /* 文本颜色 */background-color: rgba(154, 227, 36, 0.4); } .item1::before {content: "";position: absol…

【原理图专题】CIS库中有两部分组成的器件怎么查看符号库

在ICS库使用过程中&#xff0c;会遇到比如运放、MOS管等是由两个符号构成的一个器件。比如下图所示的器件&#xff1a; 为了方便我们知道内部结构&#xff0c;很可能把器件拆成两部分&#xff0c;一部分是PMOS&#xff0c;一部分是NMOS。包括大的MCU或芯片也是这样&#xff0c;…

HarmonyOS NEXT 实战之元服务:静态案例效果---查看国内航班服务

背景&#xff1a; 前几篇学习了元服务&#xff0c;后面几期就让我们开发简单的元服务吧&#xff0c;里面丰富的内容大家自己加&#xff0c;本期案例 仅供参考 先上本期效果图 &#xff0c;里面图片自行替换 效果图1完整代码案例如下&#xff1a; Index代码 import { authen…

ID读卡器TCP协议Delphi7小程序开发

Delphi 7是一款功能强大的快速应用程序开发工具&#xff0c;它提供了丰富的开发环境和组件库&#xff0c;支持多种操作系统和数据库连接&#xff0c;方便开发者进行高效的程序设计。然而&#xff0c;由于它是一款较旧的开发环境&#xff0c;在使用时需要注意兼容性和安全问题。…

C# 窗体应用程序嵌套web网页(基于谷歌浏览器内核)

有一个winform项目&#xff0c;需要借助一个web项目来显示&#xff0c;并且对web做一些操作,web页目是需要用谷歌内核&#xff0c;基于谷歌 Chromium项目的开源Web Browser控件来开发写了一个demo。 安装步骤 第一步&#xff1a;右键项目&#xff0c;点击 管理NuGet程序包 , 输…

SRA Toolkit简单使用(prefetch和fastq-dump)

工具下载网址&#xff1a; 01. 下载 SRA Toolkit ncbi/sra-tools 维基https://github.com/ncbi/sra-tools/wiki/01.-Downloading-SRA-Toolkit 我下载的是linux 3.0.10版&#xff0c;目前最新版如下&#xff1a;https://ftp-trace.ncbi.nlm.nih.gov/sra/sdk/3.1.1/sratoolkit.3…