springboot+vue实现文件上传

https://blog.csdn.net/mqingo/article/details/84869841

技术:

后端:springboot

前端框架:vue

数据库:mysql

pom.xml:

<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
controller:

@RestController
@RequestMapping("/yfjs")
@CrossOrigin
public class YFJSController {

@Autowired
private YFJSService yfjsService;
@Autowired
private FJSCService fjscService;

private String url;

@RequestMapping(value="/file",produces="application/json;charset=UTF-8")
@ResponseBody
public JSONObject uploadFile(@RequestParam("file") MultipartFile file,@RequestParam("yundanhao")String yundanhao,@RequestParam("jiyunxiang_Id")String jiyunxiang_Id) {
JSONObject rst = new JSONObject();
rst.put("yundanhao",yundanhao);
rst.put("id",jiyunxiang_Id);
System.out.print("上传文件==="+"\n");
//判断文件是否为空
if (file.isEmpty()) {
rst.put("msg","文件为空");
return rst;
}
// 获取文件名
String fileName = file.getOriginalFilename();
// System.out.print("上传的文件名为: "+fileName+"\n");

fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
System.out.print("(加个时间戳,尽量避免文件名称重复)保存的文件名为: "+fileName+"\n");
//加个时间戳,尽量避免文件名称重复
//String path = "/opt/apache-tomcat-8.0.50/webapps/img/" +fileName;
//String path = "/opt/apache-tomcat-8.0.50/webapps/img/" +fileName;
String path = "/opt/tomcat/apache-tomcat-8.0.50/webapps/img/" +fileName;
//String path = "E:/fileUpload/" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + "_" + fileName;
//文件绝对路径
System.out.print("保存文件绝对路径"+path+"\n");
//创建文件路径
File dest = new File(path);
//判断文件是否已经存在
if (dest.exists()) {
rst.put("msg","文件已经存在");
return rst;
}

try {
//上传文件
file.transferTo(dest); //保存文件
System.out.print("保存文件路径"+path+"\n");
//url="http://你自己的域名/项目名/images/"+fileName;//正式项目
url="http://测试服务器:tomcat端口号/img/"+fileName;//本地运行项目
//url="http://正式服务器2:tomcat端口号/img/"+fileName;//本地运行项目
JSONObject param = new JSONObject();
param.put("name", fileName);
param.put("url", url);
param.put("yundanhao", yundanhao);
param.put("jiyunxiang_Id", jiyunxiang_Id);
JSONObject param1 = new JSONObject();
param1.put("name", fileName);
param1.put("yundanhao", yundanhao);
param1.put("jiyunxiang_Id", jiyunxiang_Id);
System.out.print("插入结果"+yundanhao+jiyunxiang_Id+"\n");
fjscService.deleteFJSC(param1);
System.out.print("插入结果"+yundanhao+jiyunxiang_Id+"\n");
int jieguo= fjscService.insertUrl(param);
System.out.print("插入结果"+jieguo+"\n");
System.out.print("保存的完整url===="+url+"\n");

} catch (IOException e) {
rst.put("msg","上传失败");
return rst;
}
rst.put("msg","上传成功");
return rst;
}
}
 service:

package com.heeexy.example.service;

import com.alibaba.fastjson.JSONObject;

public interface FJSCService {

public int insertUrl(JSONObject jsonObject);

JSONObject deleteFJSC(JSONObject jsonObject);

}
serviceImpl:

package com.heeexy.example.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.dao.FJSCDao;
import com.heeexy.example.service.FJSCService;
import com.heeexy.example.util.CommonUtil;
@Service
public class FJSCServiceImpl implements FJSCService{

@Autowired
private FJSCDao fjscDao;

@Override
public int insertUrl(JSONObject jsonObject) {
System.out.println(jsonObject.get("yundanhao").toString()+"----------------"+jsonObject.get("jiyunxiang_Id").toString());
String[] yundan = jsonObject.get("yundanhao").toString().split(",");
String[] id = jsonObject.get("jiyunxiang_Id").toString().split(",");
int res = 0;
for(int i = 0 ; i < id.length;i++){
System.out.println(id[i]+"----------------"+yundan[i]);
jsonObject.put("jiyunxiang_Id",id[i]);
jsonObject.put("yundanhao",yundan[i]);
res=fjscDao.insertUrl(jsonObject);
}
return res;
}

@Override
public JSONObject deleteFJSC(JSONObject jsonObject) {
String[] yundan = jsonObject.get("yundanhao").toString().split(",");
String[] id = jsonObject.get("jiyunxiang_Id").toString().split(",");
String[] name = jsonObject.get("name").toString().split(",");
int rst = 0 ;
for(int i = 0 ; i < id.length;i++){
jsonObject.put("jiyunxiang_Id",id[i]);
jsonObject.put("yundanhao",yundan[i]);
jsonObject.put("name",name[i]);
rst = fjscDao.deleteFJSC(jsonObject);
if(rst==0){
jsonObject.put("msg", "删除失败");
break;
}
}
if(rst>0){
jsonObject.put("msg", "删除成功");

}
return jsonObject;

}

public List<String> getList(String id) {
List<String> list = new ArrayList<String>();

String[] str = id.split(",");
for (int i = 0; i < str.length; i++) {
list.add(str[i]);
}
return list;

}

}
dao:

package com.heeexy.example.dao;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.heeexy.example.bean.FJSC;

public interface FJSCDao {

public int insertUrl(JSONObject param);

int deleteFJSC(JSONObject jsonObject);

}
mapper:

<?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.heeexy.example.dao.FJSCDao">

<resultMap type="com.heeexy.example.bean.FJSC" id="FJSCMap">
<id column="id" property="id"/>
<result column="url" property="url"/>
<result column="name" property="name"/>
<result column="yundanhao" property="yundanhao"/>
<result column="jiyunxiang_Id" property="jiyunxiang_Id"/>
<result column="dr" property="dr"/>

</resultMap>

<insert id="insertUrl" parameterType="com.alibaba.fastjson.JSONObject">
insert into fjsc (name,url,yundanhao,jiyunxiang_Id) values (#{name},#{url},#{yundanhao},#{jiyunxiang_Id})
</insert>

<delete id="deleteFJSC" parameterType="com.alibaba.fastjson.JSONObject">
delete from fjsc where yundanhao = #{yundanhao} and jiyunxiang_Id = #{jiyunxiang_Id} and name=#{name}
</delete>

</mapper>
vue:

<el-button type="primary" icon="plus" @click="queren(sels)" :disabled="this.sels.length === 0" v-if="hasPerm(‘yfjs:querens‘)">文件上传</el-button>

import qs from "qs";
import axios from ‘axios‘;

export default {
data() {
return {
res:"",
file: ‘‘,
excelfile: ‘‘,
sels: [], //选中的值显示
tableList: [],
listXX:[],
listFJ:[],
total: 0,
start: 0,
size: 10,

totalCount: 0, //分页组件--数据总条数
list: [], //表格的数据
listLoading: false, //数据加载等待动画
listQuery: {
pageNum: 1, //页码
pageRow: 20, //每页条数
bancihao: "",
yundan:"",
biduizhuangtai: "",
userId1:this.$store.getters.userId,
rolue:"",
},
rolesname: this.$store.getters.role,
dialogStatu: "queren",
dialogFormVisibles: false,
textMaps: {
queren: "确认"
},

dialogFormVisible: false,

qrxx: {
yundan:"",
id: "",
huming: "",
kaihuyinhang: "",
zhanghao: "",
shuiwudengjihao: "",
userId: "",
deleteflag: "",
yundanhao:"",
jiyunxiang_id:"",
yundanhao:""
},
editObj:{
id:‘‘,
}

};
},

methods: {
getFile: function (event) {

this.file = event.target.files[0];

},
getexcelFile: function (event) {

this.excelfile = event.target.files[0];

},
excelFilesubmit: function (event) {

if (this.excelfile == null || this.excelfile == ‘‘) {
alert("文件为空,请选择文件进行导入");
return;
}
//阻止元素发生默认的行为
event.preventDefault();
let formData = new FormData();
formData.append("file", this.excelfile);
var url = this.HOST + "/ysjhqr/upload";
axios.post(url, formData)
.then(function (response) {
alert(response.data);
console.log(response);
window.location.reload();
}).catch(function (error) {
alert("比对数据失败,请核对excel表格数据");
console.log(error);
});
},
getfujianList: function (yundanhao,id){
this.api({
url: "/yfjs/selectFJSC",
method: "post",
params: {
yundanhao:yundanhao,
id:id,
}
}).then((data) => {
this.$set(this.listFJ = data.list);
this.listLoading = false;
console.log(data);
}).catch((aa) => {
console.log(aa)
});

},
fujianshangchuan: function (event) {
if (this.file == null || this.file == ‘‘) {
alert("文件为空,请选择文件进行导入");
return;
}
//阻止元素发生默认的行为
event.preventDefault();
let formData = new FormData();
var yundan = this.qrxx.yundan;
var id = this.qrxx.id;
formData.append("file", this.file);
formData.append("yundanhao",yundan);
formData.append("jiyunxiang_Id",id);

var url = this.HOST + "/yfjs/file";
this.$axios.post(url, formData)
.then(data => {
console.log(data);
this.getfujianList(data.data.yundanhao,data.data.id);

})
.catch(function (error) {
alert("上传失败");
console.log(error);
alert(error);

});

},

getLists() {
//查询列表
if (!this.hasPerm("yfjs:lists")) {
return;
}

this.listLoading = true;
this.listQuery.rolue = this.$store.getters.role
this.api({
url: "/yfjs/listYFJSS",
method: "get",
params: this.listQuery
}).then(data => {
this.listLoading = false;
this.list = data.list;
this.totalCount = data.totalCount;
console.log(data);
});

},
handleSizeChange(val) {
//改变每页数量
this.listQuery.pageRow = val;
this.handleFilter();
},
handleFilter() {
//查询事件
this.listQuery.pageNum = 1;
this.getLists();
},
handleCurrentChange(val) {
//改变页码
this.listQuery.pageNum = val;
this.getLists();
},
getIndex($index) {
// alert($index);
//表格序号
return (this.listQuery.pageNum - 1) * this.listQuery.pageRow + $index + 1;
},
queren(sels) {
//显示新增对话框

var ids = [];
sels.forEach(element => {
ids.push(element.id);
});

this.qrxx.id = ids.join(",");
var yundans = [];
sels.forEach(element => {
yundans.push(element.yundanhao);
});

this.qrxx.yundan = yundans.join(",");
this.qrxx.huming = "";
this.qrxx.kaihuyinhang = "";
this.qrxx.zhanghao = "";
this.qrxx.shuiwudengjihao = "",
this.qrxx.userId = this.$store.getters.userId;
this.qrxx.deleteflag = 0;
this.dialogStatu = "queren";
this.dialogFormVisibles = true;
},

selsChange(sels) {
this.sels = sels;
},

}
};
</script>

数据库:

---------------------
作者:mqingo
来源:CSDN
原文:https://blog.csdn.net/mqingo/article/details/84869841
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/ceshi2016/p/11010384.html

时间: 2024-10-04 11:55:06

springboot+vue实现文件上传的相关文章

Springboot如何启用文件上传功能

网上的文章在写 "springboot文件上传" 时,都让你加上模版引擎,我只想说,我用不上,加模版引擎,你是觉得我脑子坏了,还是觉得我拿不动刀了. springboot如何启用文件上传功能: 其实你啥都不用做,直接用就是了.文件上传相关的随着你的webStarter引入,就被引入到你的项目里面了. POM依赖: 代码: 注意事项: springboot文件上传 单个请求包含的文件默认大小:1MB-10MB 请求格式POST 参数格式form-data 如果出错了,请仔细查看报错信息!

springboot框架,文件上传问题===org.springframework.web.HttpMediaTypeNotSupportedException: Content type &#39;multipart/form-data;

使用IDEA开发springboot项目,需求中要提交数据项和文件上传,同时接收实体bean对象和文件,后台Controller接收配置方式: Controller代码如下: 1 @RequestMapping(value="/comment",method = RequestMethod.POST) 2 public @ResponseBody RetResult saveIndustryComment(HttpServletRequest request,@RequestParam

SpringBoot: 6.文件上传(转)

1.编写页面uploadFile.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>上传文件</title> </head> <body> <form action="uploadFile" method="post" enct

Eclipse搭建springboot项目(三)文件上传

知识点:SpringBoot2.x文件上传:HTML页面文件上传和后端处理 1.springboot文件上传 MultipartFile file,源自SpringMVC 1)静态页面直接访问:localhost:8080/index.html 注意点:如果想要直接访问html页面,则需要把html放在springboot默认加载的文件夹下面 2)MultipartFile 对象的transferTo方法,用于文件保存(效率和操作比原先用FileOutStream方便和高效) 访问路径 http

Minio 整合springboot 开发 实现文件上传

Minio 作为对象存储,灵活方便,结合java 实现minio 文件上传 1.搭建maven环境,添加依赖包 <properties> <minio.version>4.0.0</minio.version></properties> <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <versio

springboot最全文件上传步骤,详细,ajax文件上传,formdata封装

话不多说上代码 jsp页面: <form id="updateForm" enctype="multipart/form-data"> <input type="hidden" name="uId"> <div class="form-group"> <label class="control-label">商品名称:</label&

vue大文件上传组件选哪个好?

需求:项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在500M内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以501M来进行限制. 第一步: 前端修改 由于项目使用的是BJUI前端框架,并没有使用框架本身的文件上传控件,而使用的基于jQuery的Uploadify文件上传组件,在项目使用的jslib项目中找到了BJUI框架集成jQuery Uploadify的部分,这部分代码封装在bjui-all.js文件中, 在bjui-all.js文件中的全局变量定义中有以下

springboot实现多文件上传

一说明 spingMVC支持文件上传,我们通过Apach 的 commons-fileupload 包的CommonsMultipartResolver 去实现了 spingMVC的MultipartResolver . 本文章的示例是个简单的多文件上传,根据不同的业务自行修改. 二pom.xlm <dependencies> <dependency> <groupId>commons-fileupload</groupId> <artifactId&

VUE大文件上传解决方案实例代码

需求:项目要支持大文件上传功能,经过讨论,初步将文件上传大小控制在500M内,因此自己需要在项目中进行文件上传部分的调整和配置,自己将大小都以501M来进行限制. 第一步: 前端修改 由于项目使用的是BJUI前端框架,并没有使用框架本身的文件上传控件,而使用的基于jQuery的Uploadify文件上传组件,在项目使用的jslib项目中找到了BJUI框架集成jQuery Uploadify的部分,这部分代码封装在bjui-all.js文件中, 在bjui-all.js文件中的全局变量定义中有以下