@RequestMapping(value="/ossDown",method=RequestMethod.POST)
public void ossDown(HttpServletRequest request) {
List<SpartaSubmitSubject> listS=ossService.queryOss();
String [] str=new String[listS.size()];
for(int x=0;x<listS.size();x++) {
String value=listS.get(x).getStudentId()+"_"+listS.get(x).getPaperId()+"_"+listS.get(x).getSubjectId()+"_manage.db";
str[x]=value;
}
String endpoint="oss-cn-beijing.aliyuncs.com";
String accessKeyId = "xxx";
String accessKeySecret = "xxx";
String bucketName = "xxx";
String key1="20180914/formal/answer";
String key="";
for(int x=0;x<listS.size();x++) {
key=key1+"/"+str[x]; // 路径加数据库查询出来出来对应的名字,
downDir = LogUtil.getDownloadPath(request);//得到的servlet容器跟目录
String dowDirFile = downDir+"/" +"ossDownload";
File dowFile = new File(dowDirFile);
if(!dowFile.exists()){
dowFile.mkdirs();
}
String localUrl=dowDirFile+"/"+str[x];//下载后保存本地路径(
重点########:加上需要存的名字)
OSSClient client = null;
try {
client = new OSSClient(endpoint, accessKeyId, accessKeySecret);
if(client.doesObjectExist(bucketName, key)){//如果文件存在在下载
long startTime_d = System.currentTimeMillis();
download(client, bucketName, key, localUrl);
long endTime_d = System.currentTimeMillis();
System.out.println("下载花费时间约:" + (endTime_d - startTime_d) + " ms");
}else{
System.out.println(key+"下载失败不存在");
}
} catch (Throwable e) {
System.out.println("cuowu");
e.printStackTrace();
} finally{
System.out.println("fina");
if(null != client) {
client.shutdown();
}
}
}
}
// 下载文件 具体方法
private static void download(OSSClient client, String bucketName,
String key, String filename) throws Throwable {
try {
client.getObject(new GetObjectRequest(bucketName, key), new File(filename));
} finally {
if (client != null) {
client.shutdown();
}
}
}
public static String getDownloadPath(HttpServletRequest request) {
String rootDir = request.getSession().getServletContext().getRealPath("/");
System.out.println(rootDir);
String separator=System.getProperty("file.separator");
File folder = new File(rootDir+separator+"20180915dbForDownLoad");
if(!folder.exists() && !folder.isDirectory()){
folder.mkdirs();
}
String downDir = folder.getAbsolutePath();
return downDir;
}