/**
* 附件下載
*
* @param id 附件id
* @param response
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws KeyManagementException
*/
@RequestMapping(value = "attachmentDownLoad", method = RequestMethod.GET)
public void attachmentDownLoad(@RequestParam(value = "id", required = true) String id, HttpServletResponse response)
throws IOException, NoSuchAlgorithmException, KeyManagementException {
Attachment attachment = attachmentService.selectByPrimaryKey(id);
String fileName = attachment.getFileName();
HttpsURLConnection.setDefaultHostnameVerifier(new NullHostNameVerifier());
SSLContext sc = SSLContext.getInstance("TLS");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
byte[] data = FileCopyUtils.copyToByteArray(getInputHttpsStreamByGet(attachment.getStorgeUrl()));
fileName = URLEncoder.encode(fileName, "UTF-8");
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(data);
outputStream.flush();
outputStream.close();
}
public static InputStream getInputHttpsStreamByGet(String url) {
try {
HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
conn.setReadTimeout(5000);
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");
if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = conn.getInputStream();
return inputStream;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
// TODO Auto-generated method stub
}
@Override
public X509Certificate[] getAcceptedIssuers() {
// TODO Auto-generated method stub
return null;
}
} };
public class NullHostNameVerifier implements HostnameVerifier {
/*
* (non-Javadoc)
*
* @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
* javax.net.ssl.SSLSession)
*/
@Override
public boolean verify(String arg0, SSLSession arg1) {
// TODO Auto-generated method stub
return true;
}
}