如何使用java将文件上传到谷歌云存储?

时间:2012-04-28 08:36:07

标签: google-cloud-storage

我使用org.apache.commons.fileupload上传文件
class StorageService是一种使用云存储API来存储文件的服务 这是我的代码

public class UploadFileAction extends org.apache.struts.action.Action {

private static final String SUCCESS = "success";
private StorageService storage = new StorageService();
private static final int BUFFER_SIZE = 1024 * 1024;

@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {

    ServletFileUpload upload = new ServletFileUpload();
    FileItemIterator iter = upload.getItemIterator(request);
    while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String fileName = item.getName();
        String mime = item.getContentType();
        storage.init(fileName, mime);
        InputStream is = item.openStream();

        byte[] b = new byte[BUFFER_SIZE];
        int readBytes = is.read(b, 0, BUFFER_SIZE);
        while (readBytes != -1) {
            storage.storeFile(b, BUFFER_SIZE);
            readBytes = is.read(b, 0, readBytes);
        }

        is.close();
        storage.destroy();
    }

    return mapping.findForward(SUCCESS);
}
}

package storageservice;

import com.google.appengine.api.files.*;
import com.google.appengine.api.files.GSFileOptions.GSFileOptionsBuilder;
import java.io.*;
import java.nio.channels.Channels;

public class StorageService {

private static final String BUCKET_NAME = "thoitbk";

private FileWriteChannel writeChannel = null;
private OutputStream os = null;

public void init(String fileName, String mime) throws Exception {
    FileService fileService = FileServiceFactory.getFileService();
    GSFileOptionsBuilder builder = new GSFileOptionsBuilder()
            .setAcl("public_read")
            .setBucket(BUCKET_NAME)
            .setKey(fileName)
            .setMimeType(mime);
    AppEngineFile writableFile = fileService.createNewGSFile(builder.build());
    boolean lock = true;
    writeChannel = fileService.openWriteChannel(writableFile, lock);
    os = Channels.newOutputStream(writeChannel);
}

public void storeFile(byte[] b, int readSize) throws Exception {
    os.write(b, 0, readSize);
    os.flush();
}

public void destroy() throws Exception {
    os.close();
    writeChannel.closeFinally();
}
}

在本地,这个工作正常,但在部署我的应用时出错 请帮帮我!

1 个答案:

答案 0 :(得分:1)

通过将服务帐户添加到具有可以编辑权限的团队,确保您的应用程序的服务帐户具有对相关存储桶的WRITE访问权限,或者更新存储桶acl以明确授予服务帐户写访问。有关详细信息,请参阅this question