进行文件功能的书写,依旧新建查询。
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>