comparison software/mpdl-services-new/mpiwg-mpdl-cms-web/src/de/mpg/mpiwg/berlin/mpdl/servlets/cms/GetDocument.java @ 25:e9fe3186670c default tip

letzter Stand eingecheckt
author Josef Willenborg <jwillenborg@mpiwg-berlin.mpg.de>
date Tue, 21 May 2013 10:19:32 +0200
parents
children
comparison
equal deleted inserted replaced
23:e845310098ba 25:e9fe3186670c
1 package de.mpg.mpiwg.berlin.mpdl.servlets.cms;
2
3 import java.io.BufferedInputStream;
4 import java.io.File;
5 import java.io.FileInputStream;
6 import java.io.IOException;
7 import java.io.OutputStream;
8 import java.net.URLConnection;
9
10 import javax.servlet.ServletConfig;
11 import javax.servlet.ServletException;
12 import javax.servlet.http.HttpServlet;
13 import javax.servlet.http.HttpServletRequest;
14 import javax.servlet.http.HttpServletResponse;
15
16 import de.mpg.mpiwg.berlin.mpdl.cms.document.DocumentHandler;
17
18 public class GetDocument extends HttpServlet {
19 private static final long serialVersionUID = 1L;
20 private OutputStream out = null;
21
22 public GetDocument() {
23 super();
24 }
25
26 public void init(ServletConfig config) throws ServletException {
27 super.init(config);
28 }
29
30 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
31 request.setCharacterEncoding("utf-8");
32 response.setCharacterEncoding("utf-8");
33 String id = request.getParameter("id");
34 DocumentHandler docHandler = new DocumentHandler();
35 String fullFileName = docHandler.getDocFullFileName(id);
36 File file = new File(fullFileName);
37 if (file.exists()) {
38 write(response, file);
39 } else {
40 write(response, "Document: " + id + " does not exist");
41 }
42 }
43
44 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
45 // TODO
46 }
47
48 private void write(HttpServletResponse response, File file) throws IOException {
49 String fileName = file.getName();
50 BufferedInputStream is = new BufferedInputStream(new FileInputStream(file));
51 String contentType = URLConnection.guessContentTypeFromName(fileName); // other methods: URLConnection.guessContentTypeFromStream(is); or MIMEUtils.getMIMEType(file);
52 if (contentType != null)
53 response.setContentType(contentType);
54 response.setHeader("Content-Disposition", "filename=" + fileName);
55 out = response.getOutputStream();
56 byte[] buf = new byte[20000*1024]; // 20MB buffer
57 int bytesRead;
58 while ((bytesRead = is.read(buf)) != -1) {
59 out.write(buf, 0, bytesRead);
60 }
61 is.close();
62 out.flush();
63 }
64
65 private void write(HttpServletResponse response, String str) throws IOException {
66 out = response.getOutputStream();
67 byte[] strBytes = str.getBytes("utf-8");
68 out.write(strBytes, 0, strBytes.length);
69 out.flush();
70 }
71 }