2012-04-28 126 views
2

我用org.apache.commons.fileupload上傳文件
類StorageService是使用雲存儲API來存儲文件的服務 這是我的代碼如何使用java將文件上傳到谷歌雲存儲?

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(); 
} 
} 

在本地能正常工作,但錯誤,當我部署我的應用
請幫幫我!

+0

檢查您在此程序中使用的類是否受GAE [此處](https://developers.google.com/appengine/docs/java/jrewhitelist)支持 – 2012-04-28 08:43:52

+0

錯誤讀取的內容是什麼? – 2013-01-10 01:04:44

+0

你解決了你的問題!因爲它不適用於大於32MB的文件。請 :-( – Aerox 2014-04-19 13:15:02

回答

1

確保您的應用的服務帳戶有問題,通過添加服務帳戶團隊配合可以編輯權利或其他更新桶ACL明確授予的服務帳戶寫訪問寫訪問桶。有關更多詳情,請參閱this question

相關問題