开了一个公号【小白技术圈】,发送
B03
orb03
领取java面试包过大礼包!
//FtpUtil工具类
/**
* 从ftp中下载文件
* @param path
* ftp文件路径
* @param fileName
* ftp文件名
* @return
*/
public static InputStream downFile(String path, String fileName) {
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(username, password);// 登录
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
// 说明连接成功
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return null;
}
ftp.changeWorkingDirectory(path);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
// 解决下载文件 中文名字乱码
String name = new String(ff.getName().getBytes("iso-8859-1"), "UTF-8");
return ftp.retrieveFileStream(name);
}
ftp.logout();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return null;
}
// controler层
package com.vingsoft.web.WebController;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.vingsoft.web.util.FtpUtil;
@Controller
@RequestMapping("/Down/Down.do")
public class DownController {
@RequestMapping(params = "method=downFile")
public String downFile() {
return "/web/downanniu/downanniu";
}
@RequestMapping(params = "method=downFtpFile")
public void downFtpFile(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 1.设置文件ContentType类型,自动判断下载文件类型
response.setContentType("multipart/form-data");
// ftp文件路径
String path = "/011/1/2018/0910/3405000111809101000019/";
// ftp文件名
String filename = "2414746f8e3cf462eaa51fe316ced8cb.jpg";
int status = 0;
byte b[] = new byte[1024];
// 输入流
InputStream in = null;
// 输出流
ServletOutputStream out = null;
try {
// 获取ftp中需要下载的文件名
response.setHeader("content-disposition", "attachment; filename="
+ new String(filename.getBytes("gb2312"), "ISO8859-1"));
// 从FtpUtil工具类中将ftp的地址和文件名传到‘in’中
in = FtpUtil.downFile(path, filename);
// 服务器响应获取输出文件
out = response.getOutputStream();
while (status != -1) {
status = in.read(b);
// out.write(b);
// System.err.println(status);
if (status != -1)
out.write(b, 0, status);
}
// 要求将缓冲区的数据输出到接收方。
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null)
try {
// 关闭输入流
in.close();
} catch (IOException e) {
e.printStackTrace();
}
if (out != null)
try {
// 关闭输出流
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
jsp页面
<body>
<a href="${ctx}/Down/Down.do?method=downFtpFile">点击下载</a>
</body>