Java上傳大文件 java 大文件上傳解決方案



文章插圖
Java上傳大文件 java 大文件上傳解決方案

文章插圖
1、問題在項目開發過程中 , 遇到需要將頁面上選擇的文件上傳至FTP服務器 , 遇到一些坑 , 比如上傳文件中文名亂碼 , 上傳時指定上傳目錄不能自動創建等問題 。
2、FTP上傳文件工具類
public class FtpUtil {private String hostname = "xxx";private Integer port = 21 ;private String username = "xxx";private String password = "xxx";private FTPClient client = null;public String initialize() throws Exception{client = new FTPClient();client.setControlEncoding("utf-8");client.connect(hostname, port);client.login(username, password);int replyCode = client.getReplyCode();if(!FTPReply.isPositiveCompletion(replyCode))return "Connect ftp failed";return "success";}public String uploadFile(String storePath, String fileName, String uploadFile) throws Exception {InputStream stream = new FileInputStream(new File(uploadFile));client.setFileType(client.BINARY_FILE_TYPE);this.prepareStorePath(client, storePath);client.sendCommand("OPTS UTF8", "ON");client.storeFile(fileName, stream);if (client.storeFile(fileName, stream))return "Upload file success";return "Upload file failed";}private void prepareStorePath(FTPClient client, String storePath) throws Exception{String[] split = storePath.split("\\\\");for (String str : split) {if (StringUtils.isBlank(str))continue;if (!client.changeWorkingDirectory(str)) {client.makeDirectory(str);client.changeWorkingDirectory(str);}}}}3、Application.java測試上傳
public class Application {public static void main(String[] args) throws Exception {FtpUtil ftp = new FtpUtil();ftp.initialize();ftp.uploadFile("uploads", "W3School離線手冊2017.chm", "F:\\ToolFile\\W3School離線手冊2017.chm");}}4、文件名中文亂碼解決辦法
client.sendCommand("OPTS UTF8", "ON");5、指定文件存儲目錄不能創建解決辦法
private void prepareStorePath(FTPClient client, String storePath) throws Exception{String[] split = storePath.split("\\\\");for (String str : split) {if (StringUtils.isBlank(str))continue;if (!client.changeWorkingDirectory(str)) {client.makeDirectory(str);client.changeWorkingDirectory(str);}}}
路漫漫其修遠兮 , 吾將上下而求索
【Java上傳大文件 java 大文件上傳解決方案】譯文:在追尋真理方面 , 前方的道路還很漫長 , 但我將百折不撓 , 不遺余力地去追求和探索 。