2013-02-26 71 views
1

我上傳的文件(不同的內容類型的)使用Apache文件上傳API如下:非ASCII字符不顯示在讀取從GridFS的

FileItemFactory factory = getFileItemFactory(request.getContentLength()); 
ServletFileUpload uploader = new ServletFileUpload(factory); 
uploader.setSizeMax(maxSize); 
uploader.setProgressListener(listener); 

List<FileItem> uploadedItems = uploader.parseRequest(request); 

...將文件保存到使用以下方法GridFS的:

public String saveFile(InputStream is, String contentType) throws UnknownHostException, MongoException { 
    GridFSInputFile in = getFileService().createFile(is); 
    in.setContentType(contentType); 
    in.save(); 
    ObjectId key = (ObjectId) in.getId(); 
    return key.toStringMongod(); 
} 

...調用saveFile的()如下:

saveFile(fileItem.getInputStream(), fileItem.getContentType()) 

和採用t GridFS的閱讀他下面的方法:

public void writeFileTo(String key, HttpServletResponse resp) throws IOException { 
    GridFSDBFile out = getFileService().findOne(new ObjectId(key)); 
    if (out == null) { 
     throw new FileNotFoundException(key); 
    } 
    resp.setContentType(out.getContentType()); 
    out.writeTo(resp.getOutputStream()); 
} 

我的servlet代碼下載文件:

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
    String uri = req.getRequestURI(); 

    String[] uriParts = uri.split("/"); // expecting "/content/[key]" 

    // third part should be the key 
    if (uriParts.length == 3) { 
     try { 
      resp.setDateHeader("Expires", System.currentTimeMillis() + (CACHE_AGE * 1000L)); 
      resp.setHeader("Cache-Control", "max-age=" + CACHE_AGE); 
      resp.setCharacterEncoding("UTF-8"); 

      fileStorageService.writeFileTo(uriParts[2], resp); 
     } 
     catch (FileNotFoundException fnfe) { 
      resp.sendError(HttpServletResponse.SC_NOT_FOUND); 
     } 
     catch (IOException ioe) { 
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 
     } 
    } 
    else { 
     resp.sendError(HttpServletResponse.SC_BAD_REQUEST); 
    } 
} 

然而, 所有非ASCII字符都顯示爲'?'在網頁上與編碼集UTF-8使用到:

<meta http-equiv="content-type" content="text/html; charset=UTF-8"> 

任何幫助將不勝感激!

+0

如何保存文件?在保存或讀取文件時,您的代碼無法識別內容是否損壞。一個問題是,resp.setCharacterEncoding對resp.getOutputStream()返回的OutputStream沒有任何影響,我不明白任何(哪個?)HTML頁面上的Content-Type元首對你存儲的數據有什麼影響在GridFS中。 – jarnbjo 2013-02-26 18:48:05

+0

@jarnbjo,我已經添加了從上面的HttpServletRequest讀取的代碼。該代碼使用Apache Commons FileUpload API。 – XiX 2013-02-27 08:41:46

回答

0

道歉你的時間!這是我的錯誤。代碼或GridFS沒有任何問題。我的測試文件的編碼是錯誤的。

0
resp.setContentType("text/html; charset=UTF-8"); 

原因:只傳遞內容類型和二進制InputStream。

public void writeFileTo(String key, HttpServletResponse resp) throws IOException { 
    GridFSDBFile out = getFileService().findOne(new ObjectId(key)); 
    if (out == null) { 
     throw new FileNotFoundException(key); 
    } 
    resp.setContentType(out.getContentType()); // This might be a conflict 
    out.writeTo(resp.getOutputStream()); 

}