Spring + FTP 文件上傳下載
首先說一下ftp的特點是:傳輸速度快,適用于上傳大文件,適用于局域網絡。
直奔主題,這里采用apache提供的網絡包,commons-net.jar。我用的3.3。
ftp上傳需要ftp服務器。這里描述客戶端的實現。
spring 文件上傳這一塊就不做描述
直接代碼(上傳)
@RequestMapping(value = "/uploadConfigFile")
@ResponseBody
public void uploadConfigFile(@RequestParam("uploadFile") MultipartFile uploadFile){
FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("120.120.120.156",21);
ftpClient.login("user1", "user1");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
//設置上傳目錄
ftpClient.changeWorkingDirectory("/GOS_CAS/RECONVERT/cas_config_reconvert");
String fileName = new String(uploadFile.getOriginalFilename().getBytes("utf-8"),"iso-8859-1");
FTPFile[] fs = ftpClient.listFiles();
if (fs!=null && fs.length>0) {
for(int i=0;i<fs.length;i++){
if (fs[i].getName().equals(fileName)) {
ftpClient.deleteFile(fs[i].getName());
break;
}
}
}
OutputStream os = ftpClient.appendFileStream(fileName);
byte[] bytes = new byte[1024];
InputStream is = uploadFile.getInputStream();
// 開始復制 其實net已經提供了上傳的函數,但是我想可能是我這個版本有點問題 //ftpClient.storeFile("", fis); // 于是我自己write出去了,其實我想都是一樣的效果,在這里告訴大家這兩種方式都能實現 int c;
// 暫未考慮中途終止的情況
while ((c = is.read(bytes)) != -1) {
os.write(bytes, 0, c);
}
os.flush();
is.close();
os.close();
RestoreConfiguration restoreConfiguration = new RestoreConfiguration();
restoreConfiguration.setStrName(fileName);
getServiceStub().restoreConfiguration(restoreConfiguration);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
} 下載
@RequestMapping(value = "/downloadConfigFile")
public void downloadConfigFile(HttpServletResponse response,@RequestParam("fileName")String fileName) {
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
FTPClient ftpClient = new FTPClient();
try {
int reply;
ftpClient.connect("120.120.120.156",21);
ftpClient.login("user1", "user1");
reply = ftpClient.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
return;
}
ftpClient.changeWorkingDirectory("/GOS_CAS/BACKUP/cas_config_backup");//轉移到FTP服務器目錄
FTPFile[] fs = ftpClient.listFiles();
for(int i=0;i<fs.length;i++){
if(fs[i].getName().equals(fileName)){
String saveAsFileName = new String(fs[i].getName().getBytes("UTF-8"), "ISO8859-1");
response.setHeader("Content-Disposition", "attachment;fileName="+saveAsFileName);
OutputStream os = response.getOutputStream();
ftpClient.retrieveFile(fs[i].getName(), os);
os.flush();
os.close();
break;
}
}
ftpClient.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException ioe) {
}
}
}
}以上就簡單的自己總結了一下,希望對各位有點幫助,同時不足之處希望大神斧正 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!