【问题标题】:Uploading a blob from a client java application从客户端 Java 应用程序上传 Blob
【发布时间】:2015-04-15 07:40:21
【问题描述】:

我目前遇到以下问题:

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

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

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

注意:就我而言,我想将JavaFX Image 上传为Blob,但我认为这个问题一般都可以问。

更新 1: 使用FileService 可能是解决方案,正如@TejjD 所指出的那样。但是,Files 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 被识别为上传?

【问题讨论】:

  • 感谢您的评论!但是,我自己已经链接到该信息。它为我提供了关于这个问题的哪些额外信息?

标签: java google-app-engine blobstore


【解决方案1】:

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

但是,我插入的代码 sn-p 可能会回答您希望通过代码上传的问题。


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

您可以使用它来解析图像并上传它。

希望对你有帮助:)

一切顺利!

让我知道结果。

祝你好运

【讨论】:

  • 感谢您的回答@TejjD,不胜感激!但是,我在哪里可以指定需要写入的 URL?此外,FileService 已被弃用,所以我不热衷于使用它。
  • 完全没问题。很高兴我能解释一下。您希望将其写入何处?
  • 我想使用 POST url 连接将其写入Blobstore,请参阅我更新的问题。
  • 好吧,我明白你的意思了。我已经更新了我的答案,我正在努力整合你已经提供的链接上的 api,说。我会尽快就解决方案与您联系 :),我刚刚查看了您的“更新 2”,我将使用它为您寻找解决方案。谢谢
【解决方案2】:

有什么理由不使用 Google Cloud 存储而不是 blobstore? 有关 GCS 标准库的信息,请参阅 https://cloud.google.com/storage/docs/json_api/v1/libraries 或从 App Engine 更方便地访问 https://github.com/GoogleCloudPlatform/appengine-gcs-client

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-19
    • 1970-01-01
    • 2022-12-15
    • 2016-10-27
    • 1970-01-01
    • 2013-04-03
    • 2012-05-01
    • 2015-03-07
    相关资源
    最近更新 更多