use of javax.activation.MimetypesFileTypeMap in project Java-Tutorial by gpcodervn.
the class FileService method downloadFile.
@GET
@Path("/download/{type}")
public Response downloadFile(@PathParam("type") String fileType) {
String fileName = "test." + fileType;
File file = new File(BASE_FOLDER + "download/" + fileName);
/* Finding MIME type for explicitly setting MIME */
String mimeType = new MimetypesFileTypeMap().getContentType(file);
ResponseBuilder responseBuilder = Response.ok(file, mimeType);
responseBuilder.header("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
return responseBuilder.build();
}
use of javax.activation.MimetypesFileTypeMap in project gravitee-management-rest-api by gravitee-io.
the class ThemeServiceImpl method getImage.
private String getImage(String filename) {
String filepath = themesPath + "/" + filename;
try {
byte[] image = Files.readAllBytes(new File(filepath).toPath());
MimetypesFileTypeMap fileTypeMap = new MimetypesFileTypeMap();
return "data:" + fileTypeMap.getContentType(filename) + ";base64," + Base64.getEncoder().encodeToString(image);
} catch (IOException ex) {
final String error = "Error while trying to load image from: " + filepath;
LOGGER.error(error, ex);
return null;
}
}
use of javax.activation.MimetypesFileTypeMap in project ff4j by ff4j.
the class StaticResourceController method serveImage.
/*
* Load Images
*/
private void serveImage(HttpServletResponse res, String pathInfo, String resourceName) throws IOException {
try {
if (!images.containsKey(resourceName)) {
images.put(resourceName, FileUtils.loadFileAsByteArray(pathInfo));
}
MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap();
res.setContentType(mimetypesFileTypeMap.getContentType(resourceName));
res.getOutputStream().write(images.get(resourceName));
} catch (FileNotFoundException fnf) {
notFound(res, pathInfo);
}
}
use of javax.activation.MimetypesFileTypeMap in project aliyun-oss-java-sdk by aliyun.
the class CMKIDTest method testPostObjectWithCMKID.
@Test
public void testPostObjectWithCMKID() {
HttpURLConnection conn = null;
try {
final File sampleFile = createSampleFile(uploadLocalFilePath, 1 * 1024 * 1024);
String urlStr = TestConfig.OSS_TEST_ENDPOINT.replace("http://", "http://" + bucketName + ".");
Map<String, String> formFields = new LinkedHashMap<String, String>();
formFields.put("key", this.key);
formFields.put("Content-Disposition", "attachment;filename=" + sampleFile.getAbsolutePath());
formFields.put("OSSAccessKeyId", TestConfig.OSS_TEST_ACCESS_KEY_ID);
formFields.put("x-oss-server-side-encryption", ObjectMetadata.KMS_SERVER_SIDE_ENCRYPTION);
formFields.put("x-oss-server-side-encryption-key-id", TestConfig.KMS_CMK_ID);
String policy = "{\"expiration\": \"2120-01-01T12:00:00.000Z\",\"conditions\": [[\"content-length-range\", 0, 104857600]]}";
String encodePolicy = new String(Base64.encodeBase64(policy.getBytes()));
formFields.put("policy", encodePolicy);
String signaturecom = computeSignature(TestConfig.OSS_TEST_ACCESS_KEY_SECRET, encodePolicy);
formFields.put("Signature", signaturecom);
String boundary = "9431149156168";
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(5000);
conn.setReadTimeout(30000);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.6)");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
OutputStream out = new DataOutputStream(conn.getOutputStream());
if (formFields != null) {
StringBuffer strBuf = new StringBuffer();
Iterator<Map.Entry<String, String>> iter = formFields.entrySet().iterator();
int i = 0;
while (iter.hasNext()) {
Map.Entry<String, String> entry = iter.next();
String inputName = entry.getKey();
String inputValue = entry.getValue();
if (inputValue == null) {
continue;
}
if (i == 0) {
strBuf.append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
} else {
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"" + inputName + "\"\r\n\r\n");
strBuf.append(inputValue);
}
i++;
}
out.write(strBuf.toString().getBytes());
}
String contentType = new MimetypesFileTypeMap().getContentType(sampleFile.getName());
if (contentType == null || contentType.equals("")) {
contentType = "application/octet-stream";
}
StringBuffer strBuf = new StringBuffer();
strBuf.append("\r\n").append("--").append(boundary).append("\r\n");
strBuf.append("Content-Disposition: form-data; name=\"file\"; " + "filename=\"" + sampleFile.getName() + "\"\r\n");
strBuf.append("Content-Type: " + contentType + "\r\n\r\n");
out.write(strBuf.toString().getBytes());
DataInputStream in = new DataInputStream(new FileInputStream(sampleFile));
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
in.close();
byte[] endData = ("\r\n--" + boundary + "--\r\n").getBytes();
out.write(endData);
out.flush();
out.close();
strBuf = new StringBuffer();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
strBuf.append(line).append("\n");
}
System.out.println(strBuf.toString());
reader.close();
ObjectMetadata objectMetadata = ossClient.getObject(new GetObjectRequest(bucketName, key), new File(downloadLocalFilePath));
Assert.assertEquals(TestConfig.KMS_CMK_ID, objectMetadata.getServerSideEncryptionKeyId());
} catch (Exception e) {
Assert.fail(e.getMessage());
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
use of javax.activation.MimetypesFileTypeMap in project duangframework by tcrct.
the class AbstractHttpHandler method setDownloadFileContentHeader.
private static void setDownloadFileContentHeader(HttpResponse response, File file) {
MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();
response.headers().set(HttpHeaderNames.CONTENT_TYPE, mimeTypesMap.getContentType(file.getPath()));
SimpleDateFormat dateFormatter = new SimpleDateFormat(HTTP_DATE_FORMAT, Locale.US);
dateFormatter.setTimeZone(TimeZone.getTimeZone(HTTP_DATE_GMT_TIMEZONE));
// Date header
Calendar time = new GregorianCalendar();
response.headers().set(HttpHeaderNames.DATE, dateFormatter.format(time.getTime()));
// Add cache headers
time.add(Calendar.SECOND, HTTP_CACHE_SECONDS);
response.headers().set(HttpHeaderNames.EXPIRES, dateFormatter.format(time.getTime()));
response.headers().set(HttpHeaderNames.CACHE_CONTROL, "private, max-age=" + HTTP_CACHE_SECONDS);
response.headers().set(HttpHeaderNames.LAST_MODIFIED, dateFormatter.format(new Date(file.lastModified())));
// 加了以下代码才会弹窗
try {
response.headers().set(HttpHeaderNames.CONTENT_DISPOSITION, "attachment; filename=" + new String(file.getName().getBytes("GBK"), "ISO8859-1"));
} catch (UnsupportedEncodingException e) {
response.headers().set(HttpHeaderNames.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
}
}
Aggregations