SpringBoot实现文件上传、下载到服务器
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
一、SpringBoot模拟文件上传,下载
上传:文件前端传入,后端获取到文件通过输出流写入文件
下载:获取到文件路径,通过输入流读取,在通过输出流写入文件实现下载
#文件上传大小配置 单个文件大小 总的文件大小
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=100MB
org.springframework.boot
spring-boot-starter-web
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
/**
* @author: 清峰
* @date: 2020/11/1 18:31
* @code: 愿世间永无Bug!
* @description: 文件上传与下载 (伪下载 文件读写的过程)
* 上传:文件前端传入,后端获取到文件通过输出流写入文件
* 下载:获取到文件路径,通过输入流读取,在通过输出流写入文件实现下载
*
* 真正实现文件上传服务器(使用ftp协议 文件传输协议 网络访问传输协议)
* 也可以获取项目的相对路径在项目下(项目部署在了服务器上)创建一个文件夹用于保存文件,上传的文件保存在项目路径下即可(还可以将路径保存到数据库中http://localhost:8080/file/XXX)
* 下载的话:前端文件名展示,指定文件下载获取到文件名,找到路径进行文件读取写入到客户端
*/
@Slf4j //lombok提供的日志注解可直接调用 log的方法
@Controller
@RequestMapping("/file")
public class FileUploadController {
@PostMapping("/upload")
public void upload(@RequestParam("file") MultipartFile file) throws IOException {
// String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
// 放在static下的原因是,存放的是静态文件资源,即通过浏览器输入本地服务器地址,加文件名时是可以访问到的
// String path = ClassUtils.getDefaultClassLoader().getResource("").getPath()+"static/";
File targetFile = new File("C:\\Users\\ASUS\\Desktop\\file");
if (!targetFile.exists()) {
targetFile.mkdirs();
}
FileOutputStream bos = null;
try {
String str = targetFile + "\\" + file.getOriginalFilename(); //C:\Users\ASUS\Desktop\file\bg.jpg
log.info(str);
bos = new FileOutputStream(str);//FileOutputStream读取流的时候如果是文件夹,就会出错,无论怎么读,都拒绝访问,应该在读取的目录后面加上文件名
bos.write(file.getBytes()); //前端文件传过来后端将文件通过流写入文件夹中
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
bos.flush();
bos.close();
}
log.info("上传成功");
}
@GetMapping("/download")
public void download(HttpServletResponse response) throws IOException {
FileInputStream fis = null;
ServletOutputStream os = null;
try {
String filename = "bg.jpg";
String filePath = "C:\\Users\\ASUS\\Desktop\\file\\" + filename;
File file = new File(filePath);
if (file.exists()) {
//响应头的下载内容格式
response.setContentType("application/octet-stream");
response.setHeader("content-type", "application/octet-stream");
response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
fis = new FileInputStream(file);
byte[] bytes = new byte[1024];
os = response.getOutputStream();
// FileOutputStream os = new FileOutputStream(new File("C:\\Users\\ASUS\\Desktop\\"+filename));
int i = fis.read(bytes); //从文件夹中读取文件通过流写入指定文件中
while (i != -1) {
os.write(bytes);
i = fis.read(bytes);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
os.close();
fis.close();
}
log.info("下载成功");
}
}
二、SpringBoot实现文件上传至远程服务器(ftp)
FTP服务器(File Transfer Protocol Server)是在互联网上提供文件存储和访问服务的计算机,它们依照FTP协议提供服务。FTP是File Transfer Protocol(文件传输协议)。顾名思义,就是专门用来传输文件的协议。简单地说,支持FTP协议的服务器就是FTP服务器。
FTP是用来在两台计算机之间传输文件,是Internet中应用非常广泛的服务之一。它可根据实际需要设置各用户的使用权限,同时还具有跨平台的特性,快速方便地上传、下载文件。
commons-net
commons-net
3.6
log4j
log4j
1.2.17
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.TimeZone;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;
/**
* @author: 清峰
* @date: 2020/11/2 9:30
* @code: 愿世间永无Bug!
* @description:
*/
public class Ftp {
private FTPClient ftpClient;
private String strIp;
private int intPort;
private String user;
private String password;
private static Logger logger = Logger.getLogger(Ftp.class.getName());
/* *
* Ftp构造函数
*/
public Ftp(String strIp, int intPort, String user, String Password) {
this.strIp = strIp;
this.intPort = intPort;
this.user = user;
this.password = Password;
this.ftpClient = new FTPClient();
}
/**
* @return 判断是否登入成功
*/
public boolean ftpLogin() {
boolean isLogin = false;
FTPClientConfig ftpClientConfig = new FTPClientConfig();
ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
this.ftpClient.setControlEncoding("GBK");
this.ftpClient.configure(ftpClientConfig);
try {
if (this.intPort > 0) {
this.ftpClient.connect(this.strIp, this.intPort);
} else {
this.ftpClient.connect(this.strIp);
}
// FTP服务器连接回答
int reply = this.ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
this.ftpClient.disconnect();
logger.error("登录FTP服务失败!");
return isLogin;
}
this.ftpClient.login(this.user, this.password);
// 设置传输协议
this.ftpClient.enterLocalPassiveMode();
this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
logger.info("恭喜" + this.user + "成功登陆FTP服务器");
isLogin = true;
} catch (Exception e) {
e.printStackTrace();
logger.error(this.user + "登录FTP服务失败!" + e.getMessage());
}
this.ftpClient.setBufferSize(1024 * 2);
this.ftpClient.setDataTimeout(30 * 1000);
return isLogin;
}
/**
* @退出关闭服务器链接
*/
public void ftpLogOut() {
if (null != this.ftpClient && this.ftpClient.isConnected()) {
try {
boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
if (reuslt) {
logger.info("成功退出服务器");
}
} catch (IOException e) {
e.printStackTrace();
logger.warn("退出FTP服务器异常!" + e.getMessage());
} finally {
try {
this.ftpClient.disconnect();// 关闭FTP服务器的连接
} catch (IOException e) {
e.printStackTrace();
logger.warn("关闭FTP服务器的连接异常!");
}
}
}
}
/***
* 上传Ftp文件
* @param localFile 当地文件
* romotUpLoadePath上传服务器路径 - 应该以/结束
* */
public boolean uploadFile(File localFile, String romotUpLoadePath) {
BufferedInputStream inStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory(romotUpLoadePath);// 改变工作路径
inStream = new BufferedInputStream(new FileInputStream(localFile));
logger.info(localFile.getName() + "开始上传.....");
success = this.ftpClient.storeFile(localFile.getName(), inStream);
if (success == true) {
logger.info(localFile.getName() + "上传成功");
return success;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
logger.error(localFile + "未找到");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return success;
}
/***
* 下载文件
* @param remoteFileName 待下载文件名称
* @param localDires 下载到当地那个路径下
* @param remoteDownLoadPath remoteFileName所在的路径
* */
public boolean downloadFile(String remoteFileName, String localDires,
String remoteDownLoadPath) {
String strFilePath = localDires + remoteFileName;
BufferedOutputStream outStream = null;
boolean success = false;
try {
this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
outStream = new BufferedOutputStream(new FileOutputStream(
strFilePath));
logger.info(remoteFileName + "开始下载....");
success = this.ftpClient.retrieveFile(remoteFileName, outStream);
if (success == true) {
logger.info(remoteFileName + "成功下载到" + strFilePath);
return success;
}
} catch (Exception e) {
e.printStackTrace();
logger.error(remoteFileName + "下载失败");
} finally {
if (null != outStream) {
try {
outStream.flush();
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
if (success == false) {
logger.error(remoteFileName + "下载失败!!!");
}
return success;
}
/***
* @上传文件夹
* @param localDirectory
* 当地文件夹
* @param remoteDirectoryPath
* Ftp 服务器路径 以目录"/"结束
* */
public boolean uploadDirectory(String localDirectory,
String remoteDirectoryPath) {
File src = new File(localDirectory);
try {
remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
this.ftpClient.makeDirectory(remoteDirectoryPath);
// ftpClient.listDirectories();
} catch (IOException e) {
e.printStackTrace();
logger.info(remoteDirectoryPath + "目录创建失败");
}
File[] allFile = src.listFiles();
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
String srcName = allFile[currentFile].getPath().toString();
uploadFile(new File(srcName), remoteDirectoryPath);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
// 递归
uploadDirectory(allFile[currentFile].getPath().toString(),
remoteDirectoryPath);
}
}
return true;
}
/***
* @下载文件夹
* @param
* @param remoteDirectory 远程文件夹
* */
public boolean downLoadDirectory(String localDirectoryPath, String remoteDirectory) {
try {
String fileName = new File(remoteDirectory).getName();
localDirectoryPath = localDirectoryPath + fileName + "//";
new File(localDirectoryPath).mkdirs();
FTPFile[] allFile = this.ftpClient.listFiles(remoteDirectory);
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (!allFile[currentFile].isDirectory()) {
downloadFile(allFile[currentFile].getName(), localDirectoryPath, remoteDirectory);
}
}
for (int currentFile = 0; currentFile < allFile.length; currentFile++) {
if (allFile[currentFile].isDirectory()) {
String strremoteDirectoryPath = remoteDirectory + "/" + allFile[currentFile].getName();
downLoadDirectory(localDirectoryPath, strremoteDirectoryPath);
}
}
} catch (IOException e) {
e.printStackTrace();
logger.info("下载文件夹失败");
return false;
}
return true;
}
// FtpClient的Set 和 Get 函数
public FTPClient getFtpClient() {
return ftpClient;
}
public void setFtpClient(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
public static void main(String[] args) throws IOException {
Ftp ftp = new Ftp("10.3.15.1", 21, "ghips", "ghipsteam");
ftp.ftpLogin();
//上传文件夹
ftp.uploadDirectory("d://DataProtemp", "/home/data/");
//下载文件夹
ftp.downLoadDirectory("d://tmp//", "/home/data/DataProtemp");
ftp.ftpLogOut();
}
}
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/weixin_45019350/article/details/109443761
粉丝福利:实战springboot+CAS单点登录系统视频教程免费领取
???
?长按上方微信二维码 2 秒 即可获取资料
感谢点赞支持下哈
评论