簡體   English   中英

從GridFS讀取時不顯示非ASCII字符

[英]Non-ASCII Characters Not Displayed When Reading From GridFS

我使用Apache fileupload API上傳文件(具有不同的內容類型),如下所示:

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())

並使用以下方法從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">

任何幫助將不勝感激!

抱歉,抽出寶貴的時間! 這是我的錯 代碼或GridFS沒有錯。 我的測試文件的編碼錯誤。

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());

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM