81,090
社区成员
发帖
与我相关
我的任务
分享
/**
*
* 功能:上传文件附件到文件服务器
* @param request:上传文件流
* @return
* @throws IOException
*/
public static boolean upload(MultipartFile uploadFile, HttpServletRequest request, long id) {
boolean result = false;
try {
request.setCharacterEncoding("utf-8");
ftpClient.connect("ip", 21);
ftpClient.login("账号", "密码");
ftpClient.enterLocalPassiveMode();
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
mkDir("uploadFiles");// 创建目录
// 设置上传目录 must
ftpClient.changeWorkingDirectory("/" + "uploadFiles");
if (FTPReply.isPositiveCompletion(ftpClient.sendCommand("OPTS UTF8", "ON"))) {// 开启服务器对UTF-8的支持,如果服务器支持就用UTF-8编码,否则就使用本地编码(GBK).
LOCAL_CHARSET = "UTF-8";
}
String fileName = new String(uploadFile.getOriginalFilename().getBytes(LOCAL_CHARSET), SERVER_CHARSET);
fileName = id + "_" + fileName;// 构建上传到服务器上的文件名 20-文件名.后缀
FTPFile[] fs = ftpClient.listFiles(fileName);
if (fs.length == 0) {
System.out.println("this file not exist ftp");
} else if (fs.length == 1) {
System.out.println("this file exist ftp");
ftpClient.deleteFile(fs[0].getName());
}
InputStream is = uploadFile.getInputStream();
result = ftpClient.storeFile(fileName, is);
is.close();
} catch (IOException e) {
result = false;
e.printStackTrace();
} finally {
try {
ftpClient.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static void downFileByte(String fileName,HttpServletResponse resp) throws Exception {
ftpClient.connect("IP", 21);
ftpClient.login("账号", "密码");
ftpClient.enterLocalPassiveMode();
String remotePath="uploadFiles";
if(remotePath!=null && !remotePath.equals("")){
ftpClient.changeWorkingDirectory(remotePath);
}
BufferedOutputStream os = null;
byte[] return_arraybyte = null;
InputStream ins = null;
if (ftpClient != null) {
byte[] buffer = new byte[1024];
int byteread;
try {
//JAR源码存在问题,获取目录所在的文件会缺少部分,只能获取文件名称
String [] files= ftpClient.listNames();
for (String file : files) {
String f=new String(file.getBytes("ISO-8859-1"),"utf-8");//防止乱码
if (f.equals(fileName)) {
//需使用file.getName获值,若用f会乱码
ins = ftpClient.retrieveFileStream(file);
resp.reset();
resp.addHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(f, "utf-8"));
resp.setContentType("application/octet-stream");
os = new BufferedOutputStream(resp.getOutputStream());
while((byteread = ins.read(buffer)) != -1) {
os.write(buffer, 0, byteread);
}
ins.close();
os.flush();
os.close();
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnect();
try {
if (ins != null) {
ins.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (os != null) {
os.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}