Google Cloud Storage使用Java上传文件

时间:2018-10-14 19:44:20

标签: java google-cloud-platform google-cloud-storage

我正在使用Java Servlet和JSP创建一个Web应用程序,我想在JSP中创建一个上传表单,以便我的客户能够上传和下载内容。我正在使用Cloud Storage和默认存储桶上传内容。 我跟随Google在 Reading and Writing to Google Cloud Storage

上的评论

这是我的Servlet:

public class Create extends HttpServlet {

    public static final boolean SERVE_USING_BLOBSTORE_API = false;

    private final GcsService gcsService = GcsServiceFactory.createGcsService(new RetryParams.Builder()
       .initialRetryDelayMillis(10)
       .retryMaxAttempts(10)
       .totalRetryPeriodMillis(15000)
       .build());

 //[START doGet]
    @Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    GcsFilename fileName = getFileName(req);
    if (SERVE_USING_BLOBSTORE_API) {
        BlobstoreService blobstoreService =  BlobstoreServiceFactory.getBlobstoreService();
        BlobKey blobKey = blobstoreService.createGsBlobKey(
      "/gs/" + fileName.getBucketName() + "/" + fileName.getObjectName());
        blobstoreService.serve(blobKey, resp);
    } else {
      GcsInputChannel readChannel = gcsService.openPrefetchingReadChannel(fileName, 0, BUFFER_SIZE);
      copy(Channels.newInputStream(readChannel), resp.getOutputStream());
    }
}
//[END doGet]

//[START doPost]
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {     
  GcsFileOptions instance = GcsFileOptions.getDefaultInstance();
  GcsFilename fileName = getFileName(req);
  GcsOutputChannel outputChannel;
  outputChannel = gcsService.createOrReplace(fileName, instance);
  copy(req.getInputStream(), Channels.newOutputStream(outputChannel));
 }
//[END doPost]

private GcsFilename getFileName(HttpServletRequest req) {        
    String[] splits = req.getRequestURI().split("/", 4);
    if (!splits[0].equals("") || !splits[1].equals("gcs")) {
        throw new IllegalArgumentException("The URL is not formed as expected. " +
        "Expecting /gcs/<bucket>/<object>");
     }
     return new GcsFilename(splits[2], splits[3]);
}


private void copy(InputStream input, OutputStream output) throws IOException {
try {
  byte[] buffer = new byte[BUFFER_SIZE];
  int bytesRead = input.read(buffer);
  while (bytesRead != -1) {
    output.write(buffer, 0, bytesRead);
    bytesRead = input.read(buffer);
  }
} finally {
  input.close();
  output.close();
}
} 
}

我可以成功上传和下载,但只能输入文本而不是实际文件(图像,pdf),而我的问题是。 本教程用于读写文本,但是我想上传真实文件。正如您从我的jsp中看到的那样,编码类型为“文本/纯文本”:

<form action="/index.html" enctype="text/plain" method="get" name="putFile" id="putFile">
      <div>
        Bucket: <input type="text" name="bucket" />
        File Name: <input type="text" name="fileName" />
        <br /> File Contents: <br />
        <textarea name="content" id="content" rows="3" cols="60"></textarea>
        <br />
        <input type="submit" onclick='uploadFile(this)' value="Upload Content" />
      </div>
    </form>

我试图将其更改为“ multipart / form-data”并放入

<input name="content" id="content" type="file">

但这不会仅上传文件的假路径真实文件。 我想知道如何上传真实文件,任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

以下是如何将Blob上传到Cloud Storage的一个示例:

首先,您需要使用以下几行初始化存储空间:

private static Storage storage = null;

  // [START init]
  static {
    storage = StorageOptions.getDefaultInstance().getService();
  }
  // [END init]

您可以根据需要在getImageUrl行的String[] allowedExt = {"jpg", "jpeg", "png", "gif"};

上更改代码以接受不同的文件扩展名。
/**
 * Extracts the file payload from an HttpServletRequest, checks that the file extension
 * is supported and uploads the file to Google Cloud Storage.
 */
public String getImageUrl(HttpServletRequest req, HttpServletResponse resp,
                          final String bucket) throws IOException, ServletException {
  Part filePart = req.getPart("file");
  final String fileName = filePart.getSubmittedFileName();
  String imageUrl = req.getParameter("imageUrl");
  // Check extension of file
  if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
    final String extension = fileName.substring(fileName.lastIndexOf('.') + 1);
    String[] allowedExt = {"jpg", "jpeg", "png", "gif"};
    for (String s : allowedExt) {
      if (extension.equals(s)) {
        return this.uploadFile(filePart, bucket);
      }
    }
    throw new ServletException("file must be an image");
  }
  return imageUrl;
}

此处在文件名中附加了时间戳,如果要使文件名唯一,可能是个好主意。

/**
 * Uploads a file to Google Cloud Storage to the bucket specified in the BUCKET_NAME
 * environment variable, appending a timestamp to end of the uploaded filename.
 */
@SuppressWarnings("deprecation")
public String uploadFile(Part filePart, final String bucketName) throws IOException {
  DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
  DateTime dt = DateTime.now(DateTimeZone.UTC);
  String dtString = dt.toString(dtf);
  final String fileName = filePart.getSubmittedFileName() + dtString;

  // the inputstream is closed by default, so we don't need to close it here
  BlobInfo blobInfo =
      storage.create(
          BlobInfo
              .newBuilder(bucketName, fileName)
              // Modify access list to allow all users with link to read file
              .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
              .build(),
          filePart.getInputStream());
  // return the public download link
  return blobInfo.getMediaLink();
}

在本文档中,您将找到更多详细信息:https://cloud.google.com/java/getting-started/using-cloud-storage#uploading_blobs_to_cloud_storage

此示例的完整代码在github中:https://github.com/GoogleCloudPlatform/getting-started-java/blob/master/bookshelf/3-binary-data/src/main/java/com/example/getstarted/util/CloudStorageHelper.java

答案 1 :(得分:0)

我找到了解决方法。

这是我的JSP:

<form action="/create" enctype="multipart/form-data" method="post" name="putFile" id="putFile">
      <div>
        File Name: <input type="text" name="fileName" />
        <br /> File Contents: <br />
        <input type="submit" value="Upload Content" />
      </div>
</form>

当我提交表单时,它进入了这个Servlet:

//[START doPost]
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {     
  Part filePart = req.getPart("content");/*Get file from jsp*/
  /*Get file name of file from jsp*/
  String name =  Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
  GcsFileOptions instance = GcsFileOptions.getDefaultInstance();
  GcsFilename fileName = new GcsFilename(BUCKET_NAME, name);
  GcsOutputChannel outputChannel;
  outputChannel = gcsService.createOrReplace(fileName, instance);
  /*Pass the file to copy function, wich uploads the file to cloud*/
  copy(filePart.getInputStream(), Channels.newOutputStream(outputChannel));
  req.getRequestDispatcher("download.jsp").forward(req, resp);
 }
//[END doPost]

private GcsFilename getFileName(HttpServletRequest req) {        
    String[] splits = req.getRequestURI().split("/", 4);
    if (!splits[0].equals("") || !splits[1].equals("gcs")) {
        throw new IllegalArgumentException("The URL is not formed as expected. " +
        "Expecting /gcs/<bucket>/<object>");
     }
     return new GcsFilename(splits[2], splits[3]);
}


private void copy(InputStream input, OutputStream output) throws IOException {
try {
  byte[] buffer = new byte[BUFFER_SIZE];
  int bytesRead = input.read(buffer);
  while (bytesRead != -1) {
    output.write(buffer, 0, bytesRead);
    bytesRead = input.read(buffer);
  }
} finally {
  input.close();
  output.close();
}
}