SpringBoot+Jersey跨域文件上传的实现示例
作者:二十多岁想退休
在SpringBoot开发后端服务时,我们一般是提供接口给前端使用,本文主要介绍了SpringBoot+Jersey跨域文件上传的实现示例,具有一定的参考价值,感兴趣的可以了解一下
说明:本次所使用的
Spring内置的tomcat端口号为8070
tomcat文件服务器端口号为8060
uni-ui的端口号为8080
一、需要的工具
- tomcat服务器——作为文件服务器
- Spring项目文件
二、创建过程
1.配置Tomcat服务器
1.1添加upload文件夹
在Tomcat目录中你的webapps\Root文件夹下创建用于接收上传文件的upload文件夹
1.2修改confi/web.xml设置允许上传文件
<init-param>
<param-name>readonly</param-name>
<param-value>false</param-value>
</init-param>1.3修改Tomcat服务器的端口号
找到tomcat目录/conf/server.xml,端口号改为8060
<Connector port="8060" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />1.4启动Tomcat服务器
2.后台开发
2.1新建Web项目,在pom.xml中添加依赖
<!-- 文件上传:Begin -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<!-- 文件上传:End -->
<!--跨服务器上传:Begin -->
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-client</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.19</version>
</dependency>
<!--跨服务器上传:End -->
<!-- servlet依赖,用于接收多媒体文件-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>2.2application.yum配置上传文件大小
server:
port: 8070
spring:
servlet:
multipart:
#设置单个文件的大小,-1表示不限制,单位MB
max-file-size: 10MB
#设置单次请求的文件总大小,-1表示不限制,单位MB
max-request-size: 100MB3.创建工具类
3.1Jersey工具类
package com.$2332.interviewer.server.utils;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.Date;
import java.util.Random;
/**
* 跨服务器文件上传工具类
*
* @author 陈高风
*
*/
public class JesyFileUploadUtil {
/**
* 上传文件
*
* @param file --文件名
* @param serverUrl --服务器路径http://127.0.0.1:8080/ssm_image_server
* @return
* @throws IOException
*/
public static String uploadFile(MultipartFile file, String serverUrl) throws IOException {
//重新设置文件名
String newFileName = new Date().getTime()+""; //将当前时间获得的毫秒数拼接到新的文件名上
//随机生成一个3位的随机数
Random r = new Random();
for(int i=0; i<3; i++) {
newFileName += r.nextInt(10); //生成一个0-10之间的随机整数
}
//获取文件的扩展名
String orginalFilename = file.getOriginalFilename();
String suffix = orginalFilename.substring(orginalFilename.indexOf("."));
//创建jesy服务器,进行跨服务器上传
Client client = Client.create();
//把文件关联到远程服务器
//例如:http://127.0.0.1:8080/ssm_image_server/upload/123131312321.jpg
WebResource resource = client.resource(serverUrl+"/"+newFileName+suffix);
//上传
//获取文件的上传流
resource.put(String.class, file.getBytes());
//图片上传成功后要做的事儿
//1、ajax回调函数做图片回显(需要图片的完整路径)
//2、将图片的路径保存到数据库(需要图片的相对路径)
// String fullPath = serverUrl+"/upload/"+newFileName+suffix; //全路径
String relativePath = "/upload/"+newFileName+suffix; //相对路径
return relativePath;
}
}3.2上传文件controller层
package com.$2332.interviewer.server.controller;
import com.$2332.interviewer.server.utils.JesyFileUploadUtil;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@RestController
@RequestMapping("/upload")
@CrossOrigin(origins = "*")
public class UploadController {
@PostMapping("/file")
public String uploadFile(MultipartFile fileName){
String path = "";
try {
path = JesyFileUploadUtil.uploadFile(fileName, "http://localhost:8060/upload");
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
}
4.前端页面上传
4.1传统HTML+Vue方式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="assets/vue.min-v2.5.16.js"></script>
<script src="assets/axios.min.js"></script>
</head>
<body>
<div id="app">
<input type="file" @change="Upload" />
</div>
<script>
new Vue({
el: '#app',
data: {
},
methods: {
Upload(event){
const flie = event.target.files[0];
// 在这里进行一系列的校验
const formData = new FormData();
formData.append("fileName",flie);
axios.post('http://localhost:8070/uploadFile',formData,{
'Content-type' : 'multipart/form-data'
}).then(res=>{
console.log(res.data);
},err=>{
console.log(err)
})
}
}
});
</script>
</body>
</html>4.2uni-ui项目
上传图片
//上传标题图
uploadLogo(){
//等价代换替换this
_self = this
//第1步:打开手机相册,或文件管理器选择文件
uni.chooseImage({
count: 1, //允许上传一个文件
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album'], //从相册选择
success: function (res) {
//获得选择好的文件,他是一个数组,就算只有一个文件,那也是数组中只有一个元素
const tempFilePaths = res.tempFilePaths;
//第2步:把选择的文件上传到服务器
const uploadTask = uni.uploadFile({
url: 'http://localhost:8070/upload/file',
filePath: tempFilePaths[0],
name: 'fileName',
success: (res) => {
console.log(res.data)
_self.btnLoading = true //让按钮的进度条显示出来
_self.btnState = true //让按钮不可点击
_self.formData.logoPath = res.data
_self.btnLoading = false
}
})
//获取文件的上传进度
uploadTask.onProgressUpdate(function(res){
console.log('上传进度:'+res.progress)
console.log('已经上传的数据长度:'+res.totalBytesSent)
console.log('预计需要上传的数据总长度:'+res.totalBytesExpectedToSend)
})
}
})
},上传附件
uploadAttachment() {
_self = this
//第一步:打开文件选择器
uni.chooseFile({
count: 1, //上传文件的数量
extension: ['.pdf', '.doc', '.xlsx'],
success: function(res) {
//获取选择好的文件,他是一个数组,就算只有一个文件,那也是数组中的一个元素
const tempFilePaths = res.tempFilePaths
//第二步,把选择好的文件上传到服务器
uni.uploadFile({
url: 'http://localhost:8070/upload/file', //上传到Spring托管的服务器
filePath: tempFilePaths[0], //添加选择好的文件
name: 'fileName',
success: (res) => {
console.log(res.data)
_self.btnLoading1 = true //让按钮的进度条显示出来
_self.btnState1 = true //让按钮不可点击
_self.formData.attachmentPath = res.data
_self.btnLoading1 = false
}
})
}
});
}到此这篇关于SpringBoot+Jersey跨域文件上传的实现示例的文章就介绍到这了,更多相关SpringBoot Jersey跨域上传内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
