我正在使用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没有问题。我的测试文件编码错误。

关于java - 从GridFS读取时不显示非ASCII字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15096598/

10-11 05:01