java - 从 GridFS 读取时不显示非 ASCII 字符

标签 java http mongodb character-encoding 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);
    }
}

但是; 在编码设置为 UTF-8 的网页上,所有非 ASCII 字符都显示为“?”:

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

如有任何帮助,我们将不胜感激!

最佳答案

抱歉占用您的时间!这是我的错误。代码或 GridFS 都没有问题。我的测试文件编码错误。

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

相关文章:

java - 使用java中的子字符串从字符串中删除元音

java - 如何使用同一工作簿读取和写入Excel文件(.xlsx)?

rest - 如何使用 GCP Pub/Sub 从订阅中提取消息?

java - 为什么转换JSON RESTful Webservice后,POJO中的某些变量等于null?

java - 为什么我收到错误 "Type Mismatch"?

html - 发布 html 表单数据重定向

java - 尝试向 Grizzly+Jersey 应用程序添加过滤器时出现问题

mongodb - 为什么在 MongoDB 中完全扫描一个表需要更长的时间?

mongodb - 使用 MongoDB 配置 Sonata Media Bundle 时出现问题

node.js MongoDB查询不返回结果