Google云端存储createOrReplace文件已损坏(大小不同,...)

时间:2013-08-13 16:26:01

标签: java image google-app-engine rest google-cloud-storage

我尝试将流(restlet memoryfile)上传到gcs。但是该文件有另一个文件大小,并且有点不同,因此该文件被标记为“已损坏”。

我尝试过本地和Google应用引擎。在调试此部分时,流的大小InputStream inputStream = item.getInputStream();

看起来很好

但商店的结果不是那么大。开头有4个位:¬í[NUL][ENQ]

他们来自哪里?

List<FileItem> items;
try {
    MemoryFileItemFactory factory = new MemoryFileItemFactory();
    RestletFileUpload restletFileUpload = new RestletFileUpload(factory);
    items = restletFileUpload.parseRequest(req);
    //items = restletFileUpload.parseRepresentation(entity);
    for (FileItem item : items) {
       if (!item.isFormField()) {
           MediaType type = MediaType.valueOf(item.getContentType());
            GcsFileOptions options = new GcsFileOptions.Builder().mimeType(type.getName()).acl("public-read").build();
            GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, options);
            ObjectOutputStream oout = new ObjectOutputStream(Channels.newOutputStream(outputChannel)); 

           InputStream inputStream = item.getInputStream();
           copy(inputStream, oout);
           //oout.close();
       }
   }
} catch (FileUploadException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

private void copy(InputStream input, OutputStream output) throws IOException {
    try {
      byte[] buffer = new byte[BUFFER_SIZE];
      int bytesRead = input.read(buffer);
      while (bytesRead != -1) {
        output.write(buffer, 0, bytesRead);
        bytesRead = input.read(buffer);
      }
    } finally {
      input.close();
      output.close();
    }
}

private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
  .initialRetryDelayMillis(10)
  .retryMaxAttempts(10)
  .totalRetryPeriodMillis(15000)
  .build());

1 个答案:

答案 0 :(得分:3)

从copy-function中删除finally close语句,然后关闭GcsOutputChannel。此外,您不需要这样做:ObjectOutputStream oout = new ObjectOutputStream(Channels.newOutputStream(outputChannel)); 也许这会增加额外的比特

类似的东西:

GcsOutputChannel outputChannel = gcsService.createOrReplace(fileName, options);
InputStream inputStream = item.getInputStream();

try {
    copy(inputStream, Channels.newOutputStream(outputChannel));
} finally {
    outputChannel.close();
    inputStream.close();
}

private void copy(InputStream input, OutputStream output) throws IOException {
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytesRead = input.read(buffer);
    while (bytesRead != -1) {
        output.write(buffer, 0, bytesRead);
        bytesRead = input.read(buffer);
    }
}