从客户端Java应用程序上载blob

时间:2015-04-15 07:40:21

标签: java google-app-engine blobstore

我目前遇到以下问题:

我想从我的客户端Java应用程序将Blob上传到Google Blobstore。在Blobstore文档(https://cloud.google.com/appengine/docs/java/blobstore/)中,介绍了如何使用Blob上传FileChooser的表单执行此操作。

但是,我想从我的代码中执行此操作,但我不知道如何在Java中将Object转换为Blob。我想在Blob中传递生成的HttpURLConnection,我已经在Google App Engine上为此创建了类。

所以我的问题是:如何从客户端Java应用程序上传Blob

注意:在我的情况下,我想将JavaFX Image上传为Blob,但我认为这个问题可以提出来。

更新1:使用FileService可能是解决方案,正如@TejjD所指出的那样。但是,文件API将被弃用,因此无用。

更新2:我在服务器上使用以下代码:

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

    //Check if there is a parameter for the outfit id
     try {
        if (!req.getParameter("id").isEmpty() && Functions.isInteger(req.getParameter("id"))) {

            //Check if the requested id exists in the Cloud SQL database
            Connection conn = ConnectionManager.connectToCloudSQL();
            GetQueryBuilder query = DataManager.executeGet(conn, req, "outfit");

            //Check result
            if (query.getResultSet() == null) {
                throw new Exception("The Outfit object with the requested ID is not yet present in the Cloud SQL database");
            }

            Map<String,List<BlobKey>> blobs = blobstoreService.getUploads(req);
            BlobKey blobKey = blobs.get("image").get(0);

            if (blobKey == null) {
                throw new Exception("No blobkey specified");
            } 
            else {

               //First create a checksum from the file
               String checkSum = this.buildCheckSum(blobKey);

               PersistenceManager pm = PMF.get().getPersistenceManager();

               //Create new outfit object
               int outfitId = Integer.parseInt(req.getParameter("id"));
               OutfitExtension outfit = new OutfitExtension();
               outfit.setId(outfitId);
               outfit.setImage(blobKey);
               outfit.setCheckSum(checkSum);

               pm.makePersistent(outfit);

            }
        }
        else {
            throw new Exception("An outfit ID needs to be added to the HTTP request and should be from type Integer only.");
        }
    } catch (Exception e) {
        res.sendError(HttpServletResponse.SC_BAD_REQUEST, "Bad request: "+e.getMessage());
    }

}

当调用某个URL时,会运行此代码(我已在web.xml中将其连接起来)。 正如您在代码中看到的那样,它大约是blobstoreService.getUploads(req)。如何直接发布Blob,将其识别为上传内容?

2 个答案:

答案 0 :(得分:1)

这是一个棘手的问题,我建议你或许看看this

但是,我正在插入一个代码段,可能会根据您希望通过代码上传来回答您的问题。


public static BlobKey toBlobstore(Blob imageData) throws FileNotFoundException, FinalizationException, LockException, IOException {
    if (null == imageData)
        return null;

    // Get a file service
    FileService fileService = FileServiceFactory.getFileService();

    // Create a new Blob file with mime-type "image/png"
    AppEngineFile file = fileService.createNewBlobFile("image/jpeg");// png

    // Open a channel to write to it
    boolean lock = true;
    FileWriteChannel writeChannel = fileService.openWriteChannel(file, lock);

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

    // Now finalize
    writeChannel.closeFinally();
    return fileService.getBlobKey(file);
}


更新:(对于POST方法):

// file Upload.java

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

public class Upload extends HttpServlet {
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
        throws ServletException, IOException {

        Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
        List<BlobKey> blobKeys = blobs.get("myFile");

        if (blobKeys == null || blobKeys.isEmpty()) {
            res.sendRedirect("/");
        } else {
            res.sendRedirect("/serve?blob-key=" + blobKeys.get(0).getKeyString());
        }
    }
}


这是您可以用来解析图像并上传它的方法。

我希望这有助于你:)

一切顺利!

让我知道结果。

祝你好运

答案 1 :(得分:0)

没有使用Google云端存储而不是blobstore的任何原因? 有关GCS标准库或https://cloud.google.com/storage/docs/json_api/v1/libraries的信息,请参阅https://github.com/GoogleCloudPlatform/appengine-gcs-client,以便更方便地从App Engine访问。