Blobstore上传文件但只有第1个1 MB

时间:2016-04-28 12:56:03

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

我有一个工作的java servlet,它会将文件上传到指定的存储桶中,但是,它只能完全上传少于1MB的文件。如果我要上传一个超过1MB的文件,只会上传第一个MB的数据,而其余文件将为空。

package com.google.appengine;



import java.io.IOException;

import java.util.List;

import java.util.Map;

import java.nio.ByteBuffer;

import java.io.PrintWriter;



import javax.servlet.*;

import javax.servlet.http.*;



import com.google.appengine.api.blobstore.BlobKey;

import com.google.appengine.api.blobstore.BlobInfo;

import com.google.appengine.api.blobstore.BlobstoreService;

import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

import com.google.appengine.api.blobstore.BlobstoreInputStream;



import com.google.appengine.tools.cloudstorage.GcsFileOptions;

import com.google.appengine.tools.cloudstorage.GcsFilename;

import com.google.appengine.tools.cloudstorage.GcsOutputChannel;

import com.google.appengine.tools.cloudstorage.GcsService;

import com.google.appengine.tools.cloudstorage.GcsServiceFactory;

import com.google.appengine.tools.cloudstorage.RetryParams;



public class upload extends HttpServlet {

    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();



    @Override

    public void doPost(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

PrintWriter out = response.getWriter();

HttpSession session = request.getSession(); 

String Bucketname = (String) session.getAttribute("BUCKET");



        Map<String, List<BlobInfo>> blobsData = blobstoreService.getBlobInfos(request);

    for (String key : blobsData.keySet())

        {

        for(BlobInfo blob:blobsData.get(key))

        {

            byte[] b = new byte[(int)blob.getSize()];

            BlobstoreInputStream in = new BlobstoreInputStream(blob.getBlobKey());

            in.read(b);



            GcsService gcsService = GcsServiceFactory.createGcsService();

            GcsFilename filename = new GcsFilename(Bucketname, blob.getFilename());

            GcsFileOptions options = new GcsFileOptions.Builder()

            .mimeType(blob.getContentType())

            //.acl("authenticated-read")

            .build();



            gcsService.createOrReplace(filename,options,ByteBuffer.wrap(b));

            in.close();

        }

        }

String SharedMessage = "File has been Uploaded Successfully!";

String SharedURL = "";

session.setAttribute("SHAREDMESSAGE",SharedMessage);

session.setAttribute("SHAREDURL",SharedURL);

response.sendRedirect("SharedResult.jsp");



    }

}

任何帮助将不胜感激。谢谢

1 个答案:

答案 0 :(得分:0)

您忽略了in.read(byte[]);的返回值。它不一定填满整个数组,特别是当数组很大时。您需要阅读,直到获得-1,这意味着该流已用完。

ByteBuffer b = ByteBuffer.allocate((int)blob.getSize());
BlobstoreInputStream in = new BlobstoreInputStream(blob.getBlobKey());
byte[] buf = new byte[8192];
int bytes = 0;
while((bytes = in.read(buf)) != -1)
    b.put(buf, 0, bytes);
b.flip();
...