1、和文件上傳一樣需要引入對應的js
2、jsp頁面
3、js
/**-模板下載-**/
$('#btn_download').on('click', function() {
var urlStrl ='downloadFile.do';
var inputValue1 = 'xxxx';
var form = $('<form></form>');
form.attr('style', 'display:none');
form.attr('target', '_blank'); //設置_blank後,下載會在新窗口打開,同時保留原來的窗口
form.attr('method', 'post');
form.attr('action', urlStrl);
var input = $('<input type="text" name="XXX" id="param1" />'); // 可以使用input來提交數據
input.attr('value', inputValue1); //在input中放入需要傳入的數據
form.append(input);
$(document.body).append(form);
form.submit();
out.clear();
out = pageContext.pushBody();
return true;
});
JAVA 後臺處理
@RequestMapping("/downloadFile.do")
public ModelAndView logDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
String remoteFilePath = Tools.getPlatConfig("FTP_FILEPATH");
String remoteFileName = Tools.getPlatConfig("FTP_FILENAME");
String localFileName = "F:/ftpfile/"+remoteFileName;
try {
FtpOperation ftp = new FtpOperation(Tools.getPlatConfig("FTP_IP"), Short.parseShort(Tools.getPlatConfig("FTP_PORT")), Tools.getPlatConfig("FTP_NAME"), Tools.getPlatConfig("FTP_PASSWORD"));
boolean downloadFileByName = ftp.downloadFileByName(remoteFilePath, remoteFileName, localFileName);
if(downloadFileByName){
//model.put("msg","下載成功");
model.put("success","true");
doExport(remoteFileName, localFileName,request,response);
}else{
throw new BusinessException("W0000-0027", "下載異常!");
}
} catch (Exception e) {
model.put("msg","出錯了");
model.put("success","false");
e.printStackTrace();
}
return /*new ModelAndView("jsonView", model)*/null;
}
/**
* 導出
* @param aFileName
* @param aFilePath
*/
public void doExport(String aFileName, String aFilePath,HttpServletRequest request,HttpServletResponse response){
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
File file = null;
System.out.println("aFileName:"+aFileName);
System.out.println("aFilePath:"+aFilePath);
file = new File(aFilePath);
try{
request.setCharacterEncoding("UTF-8");
String agent = request.getHeader("User-Agent").toUpperCase();
if ((agent.indexOf("MSIE") > 0) || ((agent.indexOf("RV") != -1) && (agent.indexOf("FIREFOX") == -1)))
aFileName = URLEncoder.encode(aFileName, "UTF-8");
else {
aFileName = new String(aFileName.getBytes("UTF-8"), "ISO8859-1");
}
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-disposition", "attachment; filename=" + aFileName);
response.setHeader("Content-Length", String.valueOf(file.length()));
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length)))
bos.write(buff, 0, bytesRead);
System.out.println("success");
bos.flush();
}catch (Exception e) {
// TODO: handle exception
System.out.println("導出文件失敗!");
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
file.delete();
} catch (Exception e) {
// LOGGER.error("導出文件關閉流出錯!", e);
}
}
}
FTP工具類
package com.nmgjc.nlps.common.utils;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
/**
*
* @author mengfanbo
*/
public class FtpOperation {
protected final static Log ftpOperationLogger = LogFactory.getLog(FtpOperation.class);
// 用戶名
private String userName = "";
// 密碼
private String userPwd = "";
// 地址
private String ip = "";
// 端口
private short port = 21;
// 上傳文件存放的目錄
// private static String UPLOAD_DIR = "print/";
// OA上傳xml文件到MpmsFtp的目錄
// private static String DOWNLOAD_DIR = "test/download";
// ftp客戶端
private FTPClient ftpClient = new FTPClient();
/**
* 構造函數,當目錄不存在的時候,創建文件夾
*/
public FtpOperation(String ip, short port, String username, String passwd) throws IOException {
this.ip = ip;
this.port = port;
this.userName = username;
this.userPwd = passwd;
connectToServer();
// 判斷指定路徑是否存在,不存在就新建目錄
// checkPathExist("test");
// checkPathExist(UPLOAD_DIR);
// checkPathExist(DOWNLOAD_DIR);
// closeConnect();
}
/**
* 查找指定目錄是否存在
*
* @param String
* filePath 要查找的目錄
* @return boolean:存在:true,不存在:false
* @throws IOException
*/
/*private static boolean checkPathExist(String filePath) throws IOException { boolean existFlag = false; try { if
* (!ftpClient.changeWorkingDirectory(filePath)) { ftpClient.makeDirectory(filePath); } } catch (Exception e) {
* e.printStackTrace(); } return existFlag; } */
/**
* 連接到ftp服務器
*/
private void connectToServer() {
ftpOperationLogger.info("ftpip====" + PubMethod.FommatValue(ip) + "======userName=====" + PubMethod.FommatValue(userName));
if (!ftpClient.isConnected()) {
int reply;
try {
// ftpClient = new FTPClient();
ftpClient.connect(ip);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setDefaultPort(port);
ftpClient.login(userName, userPwd);
reply = ftpClient.getReplyCode();
ftpClient.enterLocalActiveMode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftpClient.disconnect();
ftpOperationLogger.info("FTP server refused connection.");
}
} catch (Exception e) {
ftpOperationLogger.info("登錄ftp服務器【" + PubMethod.FommatValue(ip) + "】失敗");
e.printStackTrace();
}
}
}
/**
* 關閉連接
*/
private void closeConnect() {
try {
if (ftpClient != null) {
ftpClient.logout();
ftpClient.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 轉碼[GBK -> ISO-8859-1] 不同的平臺需要不同的轉碼
*
* @param obj
* @return
*/
private static String gbkToIso8859(Object obj) {
try {
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("GBK"), "iso-8859-1");
} catch (Exception e) {
return "";
}
}
/**
* 轉碼[ISO-8859-1 -> GBK] 不同的平臺需要不同的轉碼
*
* @param obj
* @return
*/
private static String iso8859ToGbk(Object obj) {
try {
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("iso-8859-1"), "GBK");
} catch (Exception e) {
return "";
}
}
/**
* 轉碼[GBK -> UTF-8] 不同的平臺需要不同的轉碼
*
* @param obj
* @return
*/
private static String gbkToUTF(Object obj) {
try {
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("GBK"), "UTF-8");
} catch (Exception e) {
return "";
}
}
private static String UTFToGBK(Object obj) {
try {
if (obj == null)
return "";
else
return new String(obj.toString().getBytes("UTF-8"), "GBK");
} catch (Exception e) {
return "";
}
}
/**
* 設置傳輸文件的類型[文本文件或者二進制文件]
*
* @param fileType
* --BINARY_FILE_TYPE、ASCII_FILE_TYPE
*/
private void setFileType(int fileType) {
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 查找指定目錄下面指定名稱的文件是否存在
*
* @param String
* filePath 要查找的目錄
* @param String
* fileName 要查找的文件名稱
* @return boolean:存在:true,不存在:false
* @throws IOException
*/
private boolean checkFileExist(String filePath, String fileName) throws IOException {
boolean existFlag = false;
// 跳轉到指定的文件目錄
if (filePath != null && !filePath.equals("")) {
if (filePath.indexOf("/") != -1) {
int index = 0;
while ((index = filePath.indexOf("/")) != -1) {
ftpClient.changeWorkingDirectory(filePath.substring(0, index));
filePath = filePath.substring(index + 1, filePath.length());
}
if (!filePath.equals("")) {
ftpClient.changeWorkingDirectory(filePath);
}
} else {
ftpClient.changeWorkingDirectory(filePath);
}
}
String[] fileNames = ftpClient.listNames();
if (fileNames != null && fileNames.length > 0) {
for (int i = 0; i < fileNames.length; i++) {
if (fileNames[i] != null && iso8859ToGbk(fileNames[i]).equals(fileName)) {
existFlag = true;
break;
}
}
}
ftpClient.changeToParentDirectory();
return existFlag;
}
/**
* 從ftp下載指定名稱的文件到本地
*
* @param String
* remoteFileName --服務器上的文件名(只需要文件名,比如"req_0823.doc")
* @param String
* localFileName--本地文件名(包括完整的物理路徑和文件名,比如"F:/ftpfile/req_0823.doc" ,文件名可以自己定,可以不和服務器上的名字一致)
*/
public boolean downloadFileByName(String remoteFilePath, String remoteFileName, String localFileName) throws IOException {
boolean returnValue = false;
// 下載文件
BufferedOutputStream buffOut = null;
try {
// 連接ftp服務器
connectToServer();
File localFile = new File(PubMethod.FommatValue(localFileName.substring(0, localFileName.lastIndexOf("/"))));
if (!localFile.exists()) {
localFile.mkdirs();
}
if (!checkFileExist(remoteFilePath, remoteFileName)) {
ftpOperationLogger.info("ERR : file " + remoteFilePath + "/" + remoteFileName + " does not exist, download failed!");
return false;
} else {
// 跳轉到指定的文件目錄
if (remoteFilePath != null) {
if (remoteFilePath.indexOf("/") != -1) {
int index = 0;
while ((index = remoteFilePath.indexOf("/")) != -1) {
ftpOperationLogger.info("");
ftpClient.changeWorkingDirectory(remoteFilePath.substring(0, index));
remoteFilePath = remoteFilePath.substring(index + 1, remoteFilePath.length());
ftpOperationLogger.info("remoteFilePath====" + remoteFilePath);
}
if (!remoteFilePath.equals("")) {
ftpClient.changeWorkingDirectory(remoteFilePath);
}
} else {
ftpClient.changeWorkingDirectory(remoteFilePath);
}
}
// 設置傳輸二進制文件
setFileType(FTP.ASCII_FILE_TYPE);
// 獲得服務器文件
buffOut = new BufferedOutputStream(new FileOutputStream(localFileName));
returnValue = ftpClient.retrieveFile(gbkToUTF(remoteFileName), buffOut);
// 輸出操作結果信息
if (returnValue) {
ftpOperationLogger.info("INFO: download " + remoteFilePath + "/" + remoteFileName + " from ftp : succeed!");
} else {
ftpOperationLogger.info("ERR : download " + remoteFilePath + "/" + remoteFileName + " from ftp : failed!");
}
}
// 關閉連接
closeConnect();
} catch (Exception e) {
e.printStackTrace();
returnValue = false;
// 輸出操作結果信息
ftpOperationLogger.info("ERR : download " + remoteFilePath + "/" + remoteFileName + " from ftp : failed!");
} finally {
try {
if (buffOut != null) {
buffOut.close();
}
if (ftpClient.isConnected()) {
closeConnect();
}
} catch (Exception e) {
returnValue = false;
}
}
return returnValue;
}
// 上傳文件附件到ftp
/**
*
* @param uploadFile 上傳文件本地全路徑 E:\金財\work\BTB-NLPS-名單導入模板.xlsx
* @param filelocalpath 文件名
* @param uploadpath ftp服務器上傳路徑
* @return
* @throws IOException
*/
public boolean uploadAnnexToMpmsFtp(File uploadFile, String fileName , String uploadPath) throws IOException {
boolean returnValue = false;
// 上傳文件
System.out.println("uploadFile:"+uploadFile);
System.out.println("filename:"+fileName);
System.out.println("uploadpath:"+uploadPath);
BufferedInputStream buffIn = null;
try {
connectToServer();
if (!uploadFile.exists()) {
ftpOperationLogger.info("ERR : annex named " + PubMethod.FommatValue(fileName) + " not exist, import failed!");
return false;
}/*if (!checkFileExist(localpath, filename)) {
ftpOperationLogger.info("ERR : file " + localpath + "/" + filename + " does not exist, import failed!");
return false;
}*/ else {
// 跳轉到指定的文件目錄
if (uploadPath != null) {
if (uploadPath.indexOf("/") != -1) {
int index = 0;
while ((index = uploadPath.indexOf("/")) != -1) {
ftpOperationLogger.info("");
ftpClient.changeWorkingDirectory(uploadPath.substring(0, index));
uploadPath = uploadPath.substring(index + 1, uploadPath.length());
ftpOperationLogger.info("uploadpath====" + uploadPath);
}
if (!uploadPath.equals("")) {
ftpClient.changeWorkingDirectory(uploadPath);
}
} else {
ftpClient.changeWorkingDirectory(uploadPath);
}
}
// 設置傳輸二進制文件
// setFileType(FTP.BINARY_FILE_TYPE);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
// ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
// ftpClient.setFileType(FTP.EBCDIC_FILE_TYPE);
// 設置當前數據連接模式
// ftpClient.enterLocalActiveMode(); //主動模式
ftpClient.enterLocalPassiveMode();// 被動模式
// 獲得文件
buffIn = new BufferedInputStream(new FileInputStream(uploadFile));
// 上傳文件到ftp
ftpOperationLogger.info("FTP:上傳目標路徑文件 " + PubMethod.FommatValue(fileName));
returnValue = ftpClient.storeFile(gbkToIso8859(fileName), buffIn);
// 輸出操作結果信息
if (returnValue) {
ftpOperationLogger.info("INFO: upload file " + PubMethod.FommatValue(uploadFile.getAbsolutePath()) + " to ftp : succeed!");
} else {
ftpOperationLogger.info("ERR : upload file " + PubMethod.FommatValue(uploadFile.getAbsolutePath()) + " to ftp : failed!");
}
// 關閉連接
closeConnect();
}
} catch (Exception e) {
e.printStackTrace();
returnValue = false;
ftpOperationLogger.info("ERR : upload file " + PubMethod.FommatValue(uploadFile.getAbsolutePath()) + " to ftp : failed!");
} finally {
try {
if (buffIn != null) {
buffIn.close();
}
if (ftpClient.isConnected()) {
closeConnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return returnValue;
}
/**
* 刪除服務器上文件
*
* @param fileDir
* 文件路徑
* @param fileName
* 文件名稱
* @throws IOException
*/
private boolean delFile(String fileDir, String fileName) throws IOException {
boolean returnValue = false;
try {
// 連接ftp服務器
connectToServer();
// 跳轉到指定的文件目錄
if (fileDir != null) {
if (fileDir.indexOf("/") != -1) {
int index = 0;
while ((index = fileDir.indexOf("/")) != -1) {
ftpClient.changeWorkingDirectory(fileDir.substring(0, index));
fileDir = fileDir.substring(index + 1, fileDir.length());
}
if (!fileDir.equals("")) {
ftpClient.changeWorkingDirectory(fileDir);
}
} else {
ftpClient.changeWorkingDirectory(fileDir);
}
}
// 設置傳輸二進制文件
setFileType(FTP.BINARY_FILE_TYPE);
// 獲得服務器文件
returnValue = ftpClient.deleteFile(fileName);
// 關閉連接
closeConnect();
// 輸出操作結果信息
if (returnValue) {
ftpOperationLogger.info("INFO: delete " + fileDir + "/" + fileName + " at ftp:succeed!");
} else {
ftpOperationLogger.info("ERR : delete " + fileDir + "/" + fileName + " at ftp:failed!");
}
} catch (Exception e) {
e.printStackTrace();
returnValue = false;
// 輸出操作結果信息
ftpOperationLogger.info("ERR : delete " + fileDir + "/" + fileName + " at ftp:failed!");
} finally {
try {
if (ftpClient.isConnected()) {
closeConnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return returnValue;
}
public static void main(String[] args) throws IOException {
//modify by gjq 20190109 漏洞掃描 Portability Flaw: File Separator (1 Issues)
//FtpOperation ftp = new FtpOperation("10.1.61.202", (short) 12, "ibpftp", "ibpftp");
//ftp.uploadAnnexToMpmsFtp(new File("D:\\home\\weblogic\\print\\text.txt"), "print/text1.txt");
}
}