阿里云上传下载文件(execl)
//此处参数设置在propertis内
@Value("${ftp.host}")
private String ftpHost;
@Value("${ftp.port}")
private int ftpPort;
@Value("${ftp.user}")
private String ftpUser;
@Value("${ftp.pwd}")
private String ftpPwd;
@Value("${ftp.excelpath}")
private String excelPath;
@RequestMapping(value = "export", method = RequestMethod.POST)
@ResponseBody
public String export(SysLog syslog, HttpServletRequest request) throws MalformedURLException {
List list = null;
String path = null;
ClassLoader classLoader = getClass().getClassLoader();
URL url = classLoader.getResource("template/sysExcel/log.xlsx");//日志路径
String tempFilePath = url.getFile();
String tempfolder = System.getProperty("java.io.tmpdir");//获取系统临时目录
String tempName = DateUtils.getCurrentDate() + "_" +"log.xlsx";//日志名称
try {
list = logService.getExportLogInfoList(syslog);
OutputStream os = new FileOutputStream(tempfolder + tempName);
if (list != null) {
List
ftp上传工具类
public class FtpUtils {
protected static Logger logger = LoggerFactory.getLogger(FtpUtils.class);
//ftp的ip
public final static String SERVER_HOST = "";
//ftp的端口号
public final static int SERVER_PORT = ;
//ftp的用户名
public final static String SERVER_NAME = "";
//ftp的密码
public final static String SERVER_PASSWORD = "";
//要上传的路径
public final static String SERVER_PATH = "/"
public static FTPClient ftpClient;
/****
* FtpUtils.downloadFile("127.0.0.1,21","ftpuser","xiaoyan","/excel/", "aa.xlsx", response);
* FtpUtils.uploadFile("127.0.0.1,21","ftpuser","xiaoyan","/", "excel","upload.xlsx",new FileInputStream(file));
*
*/
/****
* 获取FTP连接
*
* @return
*/
public static FTPClient getConnect(String serverHost,int serverPort,String user,String pwd) {
ftpClient = new FTPClient();
try {
ftpClient.connect(serverHost, serverPort);
ftpClient.login(user, pwd);
return ftpClient;
} catch (SocketException e) {
logger.debug("连接FTP失败:"+e.getMessage());
return null;
} catch (IOException e) {
logger.debug("连接FTP失败:"+e.getMessage());
return null;
}
}
/****
* 上传文件到FTP
* @param basePath
* @param filePath
* @param filename
* @param input
* @return
*/
public static boolean uploadFile(String serverHost,int serverPort,String user,String pwd, String filePath, String filename,InputStream input) {
boolean result = false;
FTPClient ftp = null;
try {
int reply;
ftp = getConnect(serverHost,serverPort,user,pwd);
if (ftp == null) {
return result;
}
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
// 切换到上传目录
// ftp.changeWorkingDirectory("/excel/");
if (!ftp.changeWorkingDirectory(filePath)) {
// 如果目录不存在创建目录
String[] dirs = filePath.split("/");
String tempPath = "/";
for (String dir : dirs) {
if (null == dir || "".equals(dir))
continue;
tempPath += "/" + dir;
if (!ftp.changeWorkingDirectory(tempPath)) {
if (!ftp.makeDirectory(tempPath)) {
return result;
} else {
ftp.changeWorkingDirectory(tempPath);
}
}
}
}
// 设置上传文件的类型为二进制类型
ftp.setFileType(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
// ftp.setControlEncoding("UTF-8");
// 上传文件
if (!ftp.storeFile(filename, input)) {
return result;
}
input.close();
ftp.logout();
result = true;
} catch (IOException e) {
logger.debug("上传文件到FTP失败:"+e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
logger.debug("关闭FTP连接失败:"+e.getMessage());
}
}
}
return result;
}
/****
* 删除FTP
* @param basePath
* @param filePath
* @return
*/
public static boolean deleteFile(String serverHost,int serverPort,String user,String pwd,String filePath,String fileName) {
boolean result = false;
FTPClient ftp = null;
try {
int reply;
ftp = getConnect(serverHost,serverPort,user,pwd);
if (ftp == null) {
return result;
}
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return result;
}
ftp.changeWorkingDirectory(filePath);
result = ftp.deleteFile(filePath + "/" + fileName);
ftp.logout();
return result;
} catch (IOException e) {
logger.debug("删除FTP文件失败:"+e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
logger.debug("关闭FTP连接失败:"+e.getMessage());
}
}
}
return result;
}
/****
* 获取FTP文件
*
* @param remotePath
* @param fileName
* @param localPath
* @param response
* @return
*/
public static FTPFile getFtpFile(String serverHost,int serverPort,String user,String pwd,String remotePath, String fileName) {
FTPClient ftp = null;
FTPFile file = null;
try {
int reply;
ftp = getConnect(serverHost,serverPort,user,pwd);
if (ftp == null) {
return file;
}
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return file;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
FTPFile[] fs = ftp.listFiles();
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
file = ff;
}
}
ftp.logout();
return file;
} catch (IOException e) {
logger.debug("获取FTP文件失败:"+e.getMessage());
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException e) {
logger.debug("关闭FTP连接失败:"+e.getMessage());
}
}
}
return file;
}
/****
* 下载文件
* @param remotePath FTP目录
* @param fileName 文件名
* @param response
*/
public static void downloadFile(String serverHost,int serverPort,String user,String pwd,String remotePath,String localPath, String fileName,HttpServletResponse response) {
try {
// 以流的形式下载文件。
String path=getFilePath(serverHost, serverPort, user, pwd,remotePath,localPath,fileName);
if(path==null){
return;
}
File file = new File(path);
BufferedInputStream br = new BufferedInputStream(new FileInputStream(file));
byte[] buffer = new byte[br.available()];
br.read(buffer);
br.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(file.getName().getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
response.setContentType("application/vnd.ms-excel;charset=gb2312");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException e) {
logger.debug("下载FTP文件失败:"+e.getMessage());
}
}
/***
* FTP获取文件并保存到临时目录(LINUX下临时目录会自动清理,如WINDOWS要考虑怎么清理临时目录)
* @param remotePath
* @param fileName
* @param response
* @return
*/
public static String getFilePath(String serverHost,int serverPort,String user,String pwd, String remotePath,String localPath, String fileName) {
FTPClient ftp=null ;
//String localPath=System.getProperty("java.io.tmpdir");
try {
int reply;
ftp=getConnect(serverHost,serverPort,user,pwd);
// 如果采用默认端口,可以使用ftp.connect(host)的方式直接连接FTP服务器
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return null ;
}
ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录
ftp.enterLocalPassiveMode();
FTPFile[] fs = ftp.listFiles();
int isFind=0;
for (FTPFile ff : fs) {
if (ff.getName().equals(fileName)) {
File localFile = new File(localPath + "/" + ff.getName());
OutputStream is = new FileOutputStream(localFile);
ftpClient.retrieveFile(fileName, is);
is.close();
localPath+=fileName;
isFind=1;
break;
}
}
ftp.logout();
if(isFind!=1){
return null;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return localPath;
}
阿里云上传工具类
@SuppressWarnings("restriction")
public class OSSManageUtil {
/**
* 上传OSS服务器文件 @Title: uploadFile
* @param multipartFile spring 上传的文件
* remotePath @param oss服务器二级目录
* @throws Exception 设定文件 @return String
* 返回类型 @throws
*/
@SuppressWarnings("deprecation")
public static String uploadFile(InputStream fileContent, String remotePath,String fileName) throws Exception {
//随机名处理
// fileName = "yw_" + new Date().getTime() + fileName.substring(fileName.lastIndexOf("."));
// 加载配置文件,初始化OSSClient
OSSConfigure ossConfigure = new OSSConfigure("oss.properties");
OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
ossConfigure.getAccessKeySecret());
// 定义二级目录 截去第一个字符
String remoteFilePath = remotePath.substring(0, remotePath.length()).replaceAll("\\\\", "/") + "/";
// 创建上传Object的Metadata
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(fileContent.available());
objectMetadata.setContentEncoding("utf-8");
objectMetadata.setCacheControl("no-cache");
objectMetadata.setHeader("Pragma", "no-cache");
objectMetadata.setContentType(contentType(fileName.substring(fileName.lastIndexOf("."))));
objectMetadata.setContentDisposition("inline;filename=" + fileName);
// 上传文件
ossClient.putObject(ossConfigure.getBucketName(), remoteFilePath + fileName, fileContent, objectMetadata);
// 关闭OSSClient
ossClient.shutdown();
// 关闭io流
fileContent.close();
String logPath = ossConfigure.getAccessUrl() + "/" + remoteFilePath + fileName;
return logPath;
}
// 下载文件
@SuppressWarnings({ "unused", "deprecation" })
public static void downloadFile(OSSConfigure ossConfigure, String key, String filename)
throws OSSException, ClientException, IOException {
// 初始化OSSClient
OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
ossConfigure.getAccessKeySecret());
OSSObject object = ossClient.getObject(ossConfigure.getBucketName(), key);
// 获取ObjectMeta
ObjectMetadata meta = object.getObjectMetadata();
// 获取Object的输入流
InputStream objectContent = object.getObjectContent();
ObjectMetadata objectData = ossClient.getObject(new GetObjectRequest(ossConfigure.getBucketName(), key),
new File(filename));
// 关闭数据流
objectContent.close();
}
/**
* 根据key删除OSS服务器上的文件 @Title: deleteFile @Description: @param @param
* ossConfigure @param @param filePath 设定文件 @return void 返回类型 @throws
* @throws IOException
*/
@SuppressWarnings("deprecation")
public static void deleteFile( String filePath) throws IOException {
// 加载配置文件,初始化OSSClient
OSSConfigure ossConfigure = new OSSConfigure("/oss.properties");
OSSClient ossClient = new OSSClient(ossConfigure.getEndpoint(), ossConfigure.getAccessKeyId(),
ossConfigure.getAccessKeySecret());
ossClient.deleteObject(getOSSBucketName(filePath), getOSSFileName(filePath));
}
/**
* Description: 判断OSS服务文件上传时文件的contentType @Version1.0
*
* @param FilenameExtension
* 文件后缀
* @return String
*/
public static String contentType(String FilenameExtension) {
if (FilenameExtension.equals(".BMP") || FilenameExtension.equals(".bmp")) {
return "image/bmp";
}
if (FilenameExtension.equals(".GIF") || FilenameExtension.equals(".gif")) {
return "image/gif";
}
if (FilenameExtension.equals(".JPEG") || FilenameExtension.equals(".jpeg") || FilenameExtension.equals(".JPG")
|| FilenameExtension.equals(".jpg") || FilenameExtension.equals(".PNG")
|| FilenameExtension.equals(".png")) {
return "image/jpeg";
}
if (FilenameExtension.equals(".HTML") || FilenameExtension.equals(".html")) {
return "text/html";
}
if (FilenameExtension.equals(".TXT") || FilenameExtension.equals(".txt")) {
return "text/plain";
}
if (FilenameExtension.equals(".VSD") || FilenameExtension.equals(".vsd")) {
return "application/vnd.visio";
}
if (FilenameExtension.equals(".PPTX") || FilenameExtension.equals(".pptx") || FilenameExtension.equals(".PPT")
|| FilenameExtension.equals(".ppt")) {
return "application/vnd.ms-powerpoint";
}
if (FilenameExtension.equals(".DOCX") || FilenameExtension.equals(".docx") || FilenameExtension.equals(".DOC")
|| FilenameExtension.equals(".doc")) {
return "application/msword";
}
if (FilenameExtension.equals(".XML") || FilenameExtension.equals(".xml")) {
return "text/xml";
}
if (FilenameExtension.equals(".apk") || FilenameExtension.equals(".APK")) {
return "application/octet-stream";
}
//此处需根据情况增加文件类型,才可导出成功
if (FilenameExtension.equals(".xlsx") || FilenameExtension.equals(".xlsx")) {
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
}
return "text/html";
}
public static void main(String[] args) {
try {
OSSConfigure ossConfigure = new OSSConfigure("oss.properties");
// downloadFile(ossConfigure, "http://youwo888.oss-cn-beijing.aliyuncs.com/sysLog/", "20180723040851_log.xlsx");
//deleteFile("http://ceshi1111111.oss-cn-hangzhou.aliyuncs.com/cardImage/yw_1524552090254.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
*
* @MethodName: getOSSBucketName
* @Description: 根据url获取bucketName
* @param fileUrl 文件url
* @return String bucketName
*/
private static String getOSSBucketName(String fileUrl){
String http = "http://";
String https = "https://";
int httpIndex = fileUrl.indexOf(http);
int httpsIndex = fileUrl.indexOf(https);
int startIndex = 0;
if(httpIndex==-1){
if(httpsIndex==-1){
return null;
}else{
startIndex = httpsIndex+https.length();
}
}else{
startIndex = httpIndex+http.length();
}
int endIndex = fileUrl.indexOf(".oss-");
return fileUrl.substring(startIndex, endIndex);
}
/**
*
* @MethodName: getFileName
* @Description: 根据url获取fileName
* @param fileUrl 文件url
* @return String fileName
*/
private static String getOSSFileName(String fileUrl){
String str = "aliyuncs.com/";
int beginIndex = fileUrl.indexOf(str);
if(beginIndex==-1) return null;
return fileUrl.substring(beginIndex+str.length());
}
/**
*
* @MethodName: getFileName
* @Description: 根据url获取fileNames集合
* @param fileUrl 文件url
* @return List fileName集合
*/
@SuppressWarnings("unused")
private static List getOSSFileName(List fileUrls){
List names = new ArrayList();
for (String url : fileUrls) {
names.add(getOSSFileName(url));
}
return names;
}
public static String testAddUploadFileInfo(String base64Img,String remotePath,String fileName){
try {
SerialBlob serialBlob = decodeToImage(base64Img);
InputStream binaryStream = serialBlob.getBinaryStream();
String url = OSSManageUtil.uploadFile(binaryStream, remotePath, fileName);
System.out.println(url);
return url;
}catch (Exception e) {
e.printStackTrace();
}
return "";
}
private static SerialBlob decodeToImage(String imageString) throws Exception {
BASE64Decoder decoder = new BASE64Decoder();
byte[] imageByte = decoder.decodeBuffer(imageString);
return new SerialBlob(imageByte);
}
ftp.properties
#============================#
#===== FTp settings =====#
#============================#
ftp.host=10.82.31.227
ftp.port=21
ftpGpy.host=222.240.228.72
ftpGpy.port=8021
#ftp.host=222.247.55.156
#ftp.port=8099
#ftpGpy.host=222.247.55.156
#ftpGpy.port=8099
ftp.user=ftpuser
ftp.pwd=czsm2017
ftp.imgpath=/photo/
ftp.excelpath=/excel/
ftp.pdfPath=/pdf/
ftp.historyPath=/history/
##项目路径
project.local=G:/activiti/tomcat7/webapps/lemsphoto/photo/
project.photo=http://222.240.228.72:8082/lemsfile/photo/
project.excel=http://222.240.228.72:8082/lemsfile/excel
project.pdf=http://222.240.228.72:8082/lemsfile/pdf/
project.sign=http://222.240.228.72:8082/lemsfile/sign/
project.nosign=http://222.240.228.72:8082/lemsfile/nosign/
project.history=http://222.240.228.72:8082/lemsfile/history/
#project.photo=http://222.247.55.156:8080/lemsfile/photo/
#project.excel=http://222.247.55.156:8080/lemsfile/excel
#project.pdf=http://222.247.55.156:8080/lemsfile/pdf/
#project.sign=http://222.247.55.156:8080/lemsfile/sign/
#project.nosign=http://222.247.55.156:8080/lemsfile/nosign/
#project.history=http://222.247.55.156:8080/lemsfile/history/
##\u534F\u7BA1\u901A\u9644\u4EF6
project.xgtphoto=http://222.240.228.72:8082/lemsfile/xgapp/photo/
#project.xgtphoto=http://222.247.55.156:8080/lemsfile/xgapp/photo/
##