繁体   English   中英

Google Cloud Storage使用Java上传文件

[英]Google Cloud Storage upload a file using java

我正在使用Java Servlet和JSP创建一个Web应用程序,我想在JSP中创建一个上传表单,以便我的客户能够上传和下载内容。 我正在使用Cloud Storage和默认存储桶上传内容。 我遵循了Google关于读写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());

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

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

    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中看到的那样,编码类型为"text/plain"

<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">

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

这是一个有关如何将Blob上传到Cloud Storage的示例:

首先,使用以下几行初始化存储:

private static Storage storage = null;

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

您可以根据需要,通过对String[] allowedExt = {"jpg", "jpeg", "png", "gif"};行中的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

我找到了解决方案。

这是我的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:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM