文件上传springboot+vue demo下载文件组件
分类: springboot 专栏: springboot vue 标签: 文件上传springboot+vue demo
2025-03-01 19:57:17 224浏览
可以直接复制使用
sql
-- ---------------------------- -- Table structure for fl_files -- ---------------------------- DROP TABLE IF EXISTS `fl_files`; CREATE TABLE `fl_files` ( `id` int(0) NOT NULL AUTO_INCREMENT, `tableid` int(0) DEFAULT NULL COMMENT '学习文章id', `furl` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '资料路径', `cts` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '上传时间', `fname` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '文件名称', `format` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '格式', `tablename` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic; SET FOREIGN_KEY_CHECKS = 1; ) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
bean
package com.jff.falv.bean;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("fl_files")
public class FlFiles {
@TableId(type = IdType.AUTO)
Integer id;
Integer tableid;
String furl;
String fname;
String format;
String cts;
String tablename;
}
dao
package com.jff.falv.dao;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.jff.falv.bean.FlFiles;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Component;
@Component
@Mapper
public interface FlFilesMapper extends BaseMapper<FlFiles> {
}
service
package com.jff.falv.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jff.falv.bean.FlFiles;
import com.jff.falv.bean.FlUsers;
import com.jff.falv.dao.FlFilesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class FlFilesService extends ServiceImpl<FlFilesMapper, FlFiles> {
@Autowired
FlFilesMapper filesMapper;
public List<FlFiles> getlist(FlFiles o){
LambdaQueryWrapper<FlFiles> lambdaQueryWrapper = Wrappers.lambdaQuery();
if(o!=null) {
if(o.getFname()!=null&&o.getFname().trim().length() > 0 ){
lambdaQueryWrapper.like(FlFiles::getFname,o.getFname());
}
if(o.getTablename()!=null&&o.getTablename().trim().length() > 0 ){
lambdaQueryWrapper.eq(FlFiles::getTablename,o.getTablename());
}
if(o.getTableid()!=null ){
lambdaQueryWrapper.eq(FlFiles::getTableid,o.getTableid());
}
if(o.getId()!=null ){
lambdaQueryWrapper.eq(FlFiles::getId,o.getId());
}
}
List<FlFiles> li = filesMapper.selectList(lambdaQueryWrapper);
return li;
}
public List<FlFiles> getByTbale(Integer tableid,String tablename){
LambdaQueryWrapper<FlFiles> lambdaQueryWrapper = Wrappers.lambdaQuery();
lambdaQueryWrapper.eq(FlFiles::getTableid,tableid);
lambdaQueryWrapper.eq(FlFiles::getTablename,tablename);
List<FlFiles> li = filesMapper.selectList(lambdaQueryWrapper);
return li;
}
public Integer getByTbaleCount(Integer tableid,String tablename){
LambdaQueryWrapper<FlFiles> lambdaQueryWrapper = Wrappers.lambdaQuery();
lambdaQueryWrapper.eq(FlFiles::getTableid,tableid);
lambdaQueryWrapper.eq(FlFiles::getTablename,tablename);
Integer c = filesMapper.selectCount(lambdaQueryWrapper);
return c==null?0:c;
}
}
filescontroller
package com.jff.falv.control.api;
import com.jff.falv.bean.FlFiles;
import com.jff.falv.service.FlFilesService;
import com.jff.falv.util.MessUntil;
import com.jff.falv.util.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/files")
public class FlFilesController {
@Autowired
FlFilesService filesService;
@RequestMapping("/list")
public MessUntil list(FlFiles u ) {
MessUntil mess=new MessUntil();
List<FlFiles> li=filesService.getlist(u );
return mess.succ(li);
}
@RequestMapping("/update")
public MessUntil update( FlFiles u ) {
MessUntil mess=new MessUntil();
filesService.updateById(u);
return mess.succ();
}
@RequestMapping("del")
public MessUntil del(Integer id ) {
MessUntil mess=new MessUntil();
if(id==null )return mess.error( "参数错误");
FlFiles ol=filesService.getById(id);
try{
filesService.removeById(id);
}catch (Exception e){
return mess.error( "删除失败,请先删除关联数据");
}
UploadFile.deleteFile(ol.getFurl());
return mess.succ( );
}
}
commonController
package com.jff.falv.control.api;
import com.jff.falv.bean.*;
import com.jff.falv.service.*;
import com.jff.falv.util.DateUtils;
import com.jff.falv.util.MessUntil;
import com.jff.falv.util.Sys;
import com.jff.falv.util.UploadFile;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
@CrossOrigin
@RestController
@RequestMapping("/common")
public class CommonController {
@Autowired
FlFilesService filesService;
@Autowired
FlTypeService typeService;
@Autowired
XlPsyerService psyerService;
@Autowired
FlUsersService usersService;
@Autowired
FlTestService testService;
@RequestMapping("/upimg")
public MessUntil upimg(@RequestParam("file") MultipartFile file , String type, Integer id,
Integer tableid ,String tablename) throws Exception {
MessUntil mess=new MessUntil();
String p="";
if(type.equals("faceimg")){
FlUsers u=usersService.getById(id);
UploadFile.deleteFile( u.getFaceimg() );
p= Sys.Upimg.faceimg;
String img=UploadFile.upimg(file, p);
FlUsers n=new FlUsers();
n.setId(u.getId());
n.setFaceimg(img);
usersService.updateById(n);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(img);
return mess;
}
if(type.equals("type")){
FlType u=typeService.getById(id);
UploadFile.deleteFile( u.getTimg() );
p= Sys.Upimg.type;
String img=UploadFile.upimg(file, p);
FlType n=new FlType();
n.setId(u.getId());
n.setTimg(img);
typeService.updateById(n);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(img);
return mess;
}
if(type.equals("photo")){
XlPsyer u=psyerService.getById(id);
UploadFile.deleteFile( u.getPhoto() );
p= Sys.Upimg.photo;
String img=UploadFile.upimg(file, p);
XlPsyer n=new XlPsyer();
n.setId(u.getId());
n.setPhoto(img);
psyerService.updateById(n);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(img);
return mess;
}
if(type.equals("psyer_detail")){
p= Sys.Upimg.psyer_detail;
String img=UploadFile.upimg(file, p);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(Sys.httpurl+img);
return mess;
}
if(type.equals("article_detail")){
p= Sys.Upimg.article_detail;
String img=UploadFile.upimg(file, p);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(Sys.httpurl+img);
return mess;
}
if(type.equals("forum_detail")){
p= Sys.Upimg.forum_detail;
String img=UploadFile.upimg(file, p);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(Sys.httpurl+img);
return mess;
}
if(type.equals("comment_detail")){
p= Sys.Upimg.comment_detail;
String img=UploadFile.upimg(file, p);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(Sys.httpurl+img);
return mess;
}
if(type.equals("files")){
p= Sys.Upimg.files;
FlFiles f =UploadFile.upfile(file, p);
f.setCts(DateUtils.getNowDateTsString());
f.setTableid(tableid);
f.setTablename(tablename);
filesService.save(f);
mess.setStatus(1);
mess.setMsg("已上传");
mess.setObj(f);
return mess;
}
mess.setStatus(0);
mess.setMsg("上传失败,未知错误");
return mess;
}
@RequestMapping(value = "/downfile", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public void downfile(HttpServletResponse response, String fname, String furl, String format, HttpServletRequest request) throws Exception {
String abPath = Sys.Upimg.absolute_path +furl;
if(fname.indexOf(format)==-1)fname=fname+"."+format;
String filepath = abPath;
try {
// path是指想要下载的文件的路径
File file = new File(filepath);
// 将文件写入输入流
FileInputStream fileInputStream = new FileInputStream(file);
InputStream fis = new BufferedInputStream(fileInputStream);
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.setCharacterEncoding("UTF-8");
//Content-Disposition的作用:告知浏览器以何种方式显示响应返回的文件,用浏览器打开还是以附件的形式下载到本地保存
//attachment表示以附件方式下载 inline表示在线打开 "Content-Disposition: inline; filename=文件名.mp3"
// filename表示文件的默认名称,因为网络传输只支持URL编码的相关支付,因此需要将文件名URL编码后进行传输,前端收到后需要反编码才能获取到真正的名称
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fname, "UTF-8"));
// 告知浏览器文件的大小
response.addHeader("Content-Length", "" + file.length());
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
outputStream.write(buffer);
outputStream.flush();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
uploadUtile
package com.jff.falv.util;
import java.io.*;
import java.util.Date;
import java.util.UUID;
import com.jff.falv.bean.FlFiles;
import org.springframework.web.multipart.MultipartFile;
/**
* @author jf3q.com
*
*/
public class UploadFile {
public static String upimg( MultipartFile file ,String package1 ) {
String format=file.getContentType().split("/")[1];
String path =Sys.Upimg.absolute_path+Sys.Upimg.parentPack+package1 ;
File pf=new File(path);
if(!pf.exists()){
pf.mkdirs();
}
String fileName = DateUtils.DateToString(new Date(), "MMyyyyddHHmmss")+ UUID.randomUUID().toString().replaceAll("-","").substring(0,10) +"."+format;
File targetFile = new File(path, fileName);
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
String httpimg=Sys.Upimg.parentPack+package1 +fileName;
return httpimg ;
}
public static FlFiles upfile(MultipartFile file , String package1 ) {
FlFiles f=new FlFiles();
String fname=file.getOriginalFilename();
f.setFname(fname);
String format=fname.substring(fname.lastIndexOf(".")+1,fname.length());
f.setFormat(format);
String path =Sys.Upimg.absolute_path+Sys.Upimg.parentPack+package1 ;
File pf=new File(path);
if(!pf.exists()){
pf.mkdirs();
}
String fileName = DateUtils.DateToString(new Date(), "MMyyyyddHHmmss")+ UUID.randomUUID().toString().replaceAll("-","").substring(0,10) +"."+format;
File targetFile = new File(path, fileName);
try {
file.transferTo(targetFile);
} catch (Exception e) {
e.printStackTrace();
}
String httpimg=Sys.Upimg.parentPack+package1 +fileName;
f.setFurl(httpimg);
return f ;
}
public static void deleteFile( String path ) {
if(path==null)return;
String abPath = Sys.Upimg.absolute_path +path;
File f=new File(abPath);
if(path.indexOf(Sys.Upimg.noimg)>-1)return;
if( f.exists()&&f.isFile()){
f.delete();
System.out.println("==del=file=======:"+abPath+"===========del file============================================");
}
}
}
vue
<template>
<div >
<div class="handle-box">
<el-input v-model="query.fname" placeholder="名称" class="handle-input mr10"></el-input>
<el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
<el-button type="danger" icon="el-icon-plus" @click="uploadimghandle">上传资料</el-button>
</div>
<el-table :data="tableData" style="width: 100%">
<el-table-column prop="fname" align="center" label="文件" >
<template #default="scope">
<a style="color:blue;" @click="dwnload(scope.row)">{{scope.row.fname}}</a>
</template>
</el-table-column>
<el-table-column prop="cts" align="center" label="上传时间" ></el-table-column>
<el-table-column label="操作" width="200">
<template #default="scope">
<el-button type="success" size="mini" @click="handleEdit(scope.row)">编辑</el-button>
<el-button type="danger" size="mini" @click.native="handleDelete(scope.$index, scope.row)">删除</el-button>
</template>
</el-table-column>
</el-table>
<!-- 添加或者编辑弹出框 -->
<el-dialog title="添加或编辑" :visible.sync="editVisible" append-to-body>
<el-form
label-width="120px"
:model="dataForm"
:rules="dataFormRule"
ref="dataForm"
>
<el-form-item label="文件名称" prop="fname">
<el-input v-model="dataForm.fname"></el-input>
</el-form-item>
</el-form>
<template #footer>
<span class="dialog-footer">
<el-button @click="editVisible = false">取 消</el-button>
<el-button type="primary" @click="saveEdit">确 定</el-button>
</span>
</template>
</el-dialog>
<!-- 上传图片弹出框 -->
<el-dialog title="上传资料" :visible.sync="uploadimgVisible" width="400px" append-to-body>
<el-upload
drag
:before-upload="beforeUploadFile"
:show-file-list="false"
:action=FILE_ACTION
:on-success="handleFileSuccess"
:multiple="true">
<p>点击上传</p>
</el-upload>
</el-dialog>
</div>
</template>
<script>
import PubSub from 'pubsub-js'
import {files_list, files_update, files_del } from '../../api';
export default {
name: "System",
props:{
tableid:{
type:Number,
default:'',
},
tablename:{
type:String,
default:'',
}
},
components: {
},
data() {
return {
FILE_URL:'',
FILE_ACTION:'',
uploadimgVisible:false,
lander:{},
tableData: [],
query :{
fname: '',
},
pageTotal: 0,
editVisible: false,
dataForm :{
id :'',
fname : '',
},
dataFormRule: {
fname: [{required: true, message: '不能为空', trigger: 'blur'}],
},
};
},
methods:{
dwnload(row){
window.open(this.FILE_URL+'/common/downfile?fname='+row.fname+'&furl='+row.furl+'&format='+row.format)
},
//上传图片
beforeUploadFile(){
this.loading = this.$loading({
lock: true,
text: "上传中,请稍等,,,,",
spinner: "el-icon-loading",
background: "rgba(0, 0, 0, 0.5)",
});
},
handleFileSuccess(res) {
this.loading.close();
console.log(res)
if( res.status==1){
this.$message.success( '上传成功' );
this.uploadimgVisible=false;
this.getPage();
}else{
this.$message.error( '上传失败' );
}
},
uploadimghandle( ){
this.uploadimgVisible=true;
this.FILE_ACTION=process.env.VUE_APP_API_ROOT+'/common/upimg?type=files&tableid='
+this.tableid+"&tablename="+this.tablename ;
},
// 查询操作
handleSearch (){
console.log(this.query)
this.query.pageNo = 1;
this.getPage();
},
// 分页导航
handlePageChange (val) {
this.query.pageNo = val;
this.getPage();
},
//弹出添加操作弹框
handleAdd(){
this.dataForm={}
this.editVisible = true;
},
//弹出修改操作弹框
handleEdit ( row) {
this.dataForm.id = row.id
this.dataForm.fname = row.fname
this.editVisible = true;
},
//保存操作
saveEdit(){
this.$refs.dataForm.validate(valid => {
//表单验证失败
if (!valid) {
//提示语
this.$message.error("请按提示填写表单");
this.editVisible = true;
return false;
} else {
files_update(this.dataForm).then((res) => {
this.editVisible = false;
this.getPage();
})
}
})
},
//删除操作
handleDelete(index,row){
// 二次确认删除
this.$confirm("确定要删除吗?", "提示", {
type: "warning",
})
.then(() => {
files_del({id:row.id }).then((res) => {
if(res.data.status==1){
this.$message.success("删除成功");
this.tableData.splice(index, 1);
this.getPage();
}else{
this.$notify({
title: '提示',
message: res.data.msg,
duration: 0
});
}
})
})
.catch(() => {
this.$message({
type: 'info',
message: '已取消删除'
});
});
},
//获取列表数据
getPage(){
this.query.tableid=this.tableid;
this.query.tablename=this.tablename;
files_list(this.query).then((res) => {
this.tableData = res.data.obj
this.pageTotal = res.data.obj.length//该页总共多少条记录
})
},
},
mounted() {
this.lander=JSON.parse(localStorage.loginUser)
this.FILE_URL=process.env.VUE_APP_API_ROOT
//去后端查询所有的用户给tableData赋值
PubSub.subscribe('changeFiles',(msg,index)=>{
this.tableid=parseInt(index.split('@#@')[0]);
this.tablename=index.split('@#@')[1];
this.getPage();
});
}
}
</script>
<style scoped>
.handle-box {
margin-bottom: 20px;
}
.handle-select {
width: 120px;
}
.handle-input {
width: 120px;
display: inline-block;
}
.table {
width: 100%;
font-size: 14px;
}
.red {
color: #ff0000;
}
.mr10 {
margin-right: 10px;
}
/*滚动条的宽度*/
/deep/ .el-table__body-wrapper::-webkit-scrollbar {
width: 6px;
height: 6px;
}
/*滚动条滑块*/
/deep/ .el-table__body-wrapper::-webkit-scrollbar-thumb {
background-color: #409eff;
/*border-radius: 3px;*/
}
</style>
vue是组件引入,使用消息队列传递参数
好博客就要一起分享哦!分享海报
此处可发布评论
评论(0)展开评论
暂无评论,快来写一下吧
展开评论
他的专栏
他感兴趣的技术


java
vue
springboot
Mysql
ssm
小程序
uniapp
js和jquery