0

我正在为 Java Servlet 开发代码来处理表单图像 POST ,并将该图像上传到 Google Cloud Storage。我可以使用 XMLHttpRequest 和 FormData 上传执行 ajax 调用 POST 的图像。我面临的是大多数时候存储的图像已损坏,无法打开。像这个(http://storage.googleapis.com/realtimevouchers/Porto_ribeira.jpg),但图像在我的文件系统上还可以。这可能是处理 servlet 代码中的流的错误吗?

这是servlet代码:

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");

    String ajaxUpdateResult = "";
    ServletFileUpload upload = new ServletFileUpload();
    String filePath = "";

    try {
        FileItemIterator iter = upload.getItemIterator(request);

        while (iter.hasNext()) {
            FileItemStream item = iter.next();

            String fileName = item.getName();
            System.out.println("Nome ficheiro->" + fileName);
            String mimeType = item.getContentType();
            System.out.println("mimeType->" + mimeType);
            InputStream content = item.openStream();

            // Process the input stream
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int len;
            byte[] buffer = new byte[8192];
            while ((len = content.read(buffer, 0, buffer.length)) != -1) {
                baos.write(buffer, 0, len);
            }
            int maxFileSize = 10 * (1024 * 1024); // 10 megs max
            if (baos.size() > maxFileSize) {
                throw new RuntimeException("File is > than " + maxFileSize);
            }

            FileService fileService = FileServiceFactory.getFileService();

            java.util.Date date = new java.util.Date();
            java.sql.Timestamp timeStamp = new Timestamp(date.getTime());
            System.out.println("DEBUG:upload timeStamp->" + timeStamp);

            GSFileOptionsBuilder optionsBuilder = new GSFileOptionsBuilder()
                    .setBucket(BUCKETNAME).setKey(fileName)
                    .setMimeType(mimeType).setAcl("public_read")
                    .addUserMetadata("uploadTimeStamp", timeStamp.toString());
            AppEngineFile writableFile = fileService
                    .createNewGSFile(optionsBuilder.build());

            // Open a channel to write to it
            boolean lock = true;
            FileWriteChannel writeChannel = fileService.openWriteChannel(
                    writableFile, lock);
            // Different standard Java ways of writing to the channel
            // are possible.

            // This time we write to the channel directly
            writeChannel.write(ByteBuffer.wrap(buffer));

            // Now finalize
            writeChannel.closeFinally();
            filePath = writableFile.getFullPath();

            // Do whatever with the content InputStream.
            // System.out.println(Streams.asString(content));//binary

            ajaxUpdateResult += "File " + fileName
                    + " is successfully uploaded\n\r";

        }

    } catch (FileUploadException e) {
        throw new ServletException("Parsing file upload failed.", e);
    }
    org.json.JSONObject json = new JSONObject();
    try {
        json.put("operationStatus", "SUCCESS");
        json.put("operationExecuted", "POST_TO_GCS");
        json.put("filePath", filePath);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    System.out.println("DEBUG:" + json.toString());
    log.info("LOGGER" + json.toString());
    response.getWriter().println(json.toString());
    response.getWriter().print(ajaxUpdateResult);
}
4

0 回答 0