@RequestMapping("/download/{protocolID}")
public void download(@PathVariable Long protocolID, HttpServletResponse response) {
Map<String, String> map = protocolService.getDownloadUrl(protocolID);
String downloadUrl = map.get("uploadUrl");
String downloadFilename = map.get("protocolName");
try {
String encodedFileName = encodeUrlChinese(downloadFilename);
downloadFilename = URLEncoder.encode(downloadFilename, "UTF-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + downloadFilename);
BufferedOutputStream fos = new BufferedOutputStream(response.getOutputStream());
String encodedUrl = downloadUrl.substring(0,downloadUrl.lastIndexOf("/")+1) + encodedFileName;
URL url = new URL(encodedUrl);
URLConnection urlCon = url.openConnection();
urlCon.setDoOutput(false);
InputStream fis = urlCon.getInputStream();
byte[] buffer = new byte[1024];
int r = 0;
while ((r = fis.read(buffer)) != -1) {
fos.write(buffer, 0, r);
}
fis.close();
fos.flush();
fos.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private String encodeUrlChinese(String fileName){
char[] str = fileName.toCharArray();
StringBuilder sb = new StringBuilder();
int strSize = fileName.length();
char ch;
for (int i=0,j=0; i<strSize; ++i) {
ch = str[i];
if (((ch>='A') && (ch<'Z')) ||
((ch>='a') && (ch<'z')) ||
((ch>='0') && (ch<'9'))) {
sb.append(ch);
} else if (ch == ' ') {
sb.append("%20");
} else if (ch == '.' || ch == '-' || ch == '_' || ch == '*') {
sb.append(ch);
} else {
try {
sb.append(URLEncoder.encode(ch + "", "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}