第二部分:ftp文件下载
@Controller
public class FileTransferController extends BaseController{
//临时文件存放目录
public String tempPath = FileUtil.getProjectPath()+"\\temp\\";
/**
* 文件下载
* @author zheng_liming
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/fileTransfer/download", method = RequestMethod.POST)
public void download(HttpServletRequest request,HttpServletResponse response) throws Exception{
DynamicForm dynamicForm =(DynamicForm) PlatformContext.getRequestAttribute(SystemConstants.DYNAMICFORM);
String fileName = dynamicForm.getString("fileName");
String filePath = dynamicForm.getString("filePath");
File file = new File(tempPath);
if (!file.exists()) {
file.mkdirs();
}
//连接ftp
FtpClient ftpClient = FtpUtil.connectServer(filePath);
//将ftp上的文件下载到服务器端工程目录下
boolean downResult = FileUtil.ftpDownload(ftpClient, fileName, tempPath+fileName);
if(downResult){
//将工程目录下的文件下载到客户端
downFile(tempPath,fileName);
}
//删除工程目录下文件
FileUtil.removeAllFile(tempPath);
FileUtil.removeFolder(tempPath);
}
/**
* 将服务器上的文件下载到客户端
* @author zheng_liming
* @param filePath 文件路径
* @param fileName 文件名称
*/
public void downFile(String filePath,String fileName) throws Exception{
FileInputStream fis = new FileInputStream(new File(filePath+fileName));
//设置响应头和保存文件名
HttpServletResponse response = getResponse();
response.setContentType("APPLICATION/OCTET-STREAM");
response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
//写出流信息
int b = 0;
PrintWriter out = response.getWriter();
while((b=fis.read())!=-1) {
out.write(b);
}
//关闭
fis.close();
out.close();
}
}