@RequestMapping(value = "/downFile")
@ResponseBody
public void downFile(HttpServletRequest request, HttpServletResponse response) {
BufferedInputStream input = null;
OutputStream outputStream = null;
try {
String filePath = request.getParameter("path");
filePath = filePath.replaceAll("\\\\", "/");
String fileName = getName(filePath);
response.reset();
response.setCharacterEncoding("utf-8");
response.setContentType("application/x-msdownload");
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"),"ISO8859-1"));
// endpoint,accessKeyId,accessKeySecret,bucketName是oss自帶參數,登陸oss檢視,或者給公司要,fileName是檔案上傳到oss後的檔案名
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
OSSObject object = ossClient.getObject(bucketName, fileName);
input = new BufferedInputStream(object.getObjectContent());
byte[] buffBytes = new byte[1024];
outputStream = response.getOutputStream();
int read = 0;
while ((read = input.read(buffBytes)) != -1) {
outputStream.write(buffBytes, 0, read);
}
outputStream.flush();
ossClient.shutdown();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
if (input != null) {
input.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
// 擷取添加後的檔案名稱
public String getName(String filepath) {
if (!filepath.equals(null)) {
if (filepath.contains("/")) {
return filepath.substring(filepath.lastIndexOf("/") + 1);
}
}
return "";
}