一、SpringBoot模拟檔案上傳,下載下傳
上傳:檔案前端傳入,後端擷取到檔案通過輸出流寫入檔案
下載下傳:擷取到檔案路徑,通過輸入流讀取,在通過輸出流寫入檔案實作下載下傳
#檔案上傳大小配置 單個檔案大小 總的檔案大小spring.servlet.multipart.max-file-size=10MBspring.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的方法@[email protected]("/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:甥敳獲ASUSDesktopfile"); if (!targetFile.exists()) { targetFile.mkdirs(); } FileOutputStream bos = null; try { String str = targetFile + "" + file.getOriginalFilename(); //C:甥敳獲ASUSDesktopfilebg.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:甥敳獲ASUSDesktopfile" + 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:甥敳獲ASUSDesktop"+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

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
版權聲明:本文為部落客原創文章,遵循 CC 4.0 BY-SA 版權協定,轉載請附上原文出處連結和本聲明。
本文連結:
https://blog.csdn.net/weixin_45019350/article/details/109443761