为了账号安全,请及时绑定邮箱和手机立即绑定

谷歌云存储使用java上传文件

谷歌云存储使用java上传文件

蝴蝶不菲 2021-11-17 16:51:11
我正在使用 Java servlet 和 JSP 创建一个 Web 应用程序,我想在 JSP 中创建一个上传表单,以便我的客户能够上传和下载内容。我正在使用 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());        }    }我可以成功上传和下载,但只能是文本,而不是图像、pdf 等真实文件,这是我的问题。本教程用于阅读和编写文本,但我想上传真实文件。正如您从我的 jsp 中看到的,enctype 是"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">但这不会上传真实文件,只会上传文件的假路径。我想知道如何上传真实文件,任何帮助将不胜感激。
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

我找到了解决办法。


这是我的 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();

    }

}


查看完整回答
反对 回复 2021-11-17
?
偶然的你

TA贡献1841条经验 获得超3个赞

下面是一个关于如何将 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


查看完整回答
反对 回复 2021-11-17
  • 2 回答
  • 0 关注
  • 224 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信