简体   繁体   English

如何使用java上传谷歌云存储中的文件

[英]How to upload a file in the google cloud storage using java

I have been trying for a long time to upload a file in the Google cloud store using java.我一直在尝试使用java在谷歌云存储中上传文件。 By goggling I have found this code, but cant able to understand exactly.通过护目镜,我找到了这段代码,但无法准确理解。 Can anyone please customize this one to upload a file in the GCS?任何人都可以自定义这个以在 GCS 中上传文件吗?

// Given
InputStream inputStream;  // object data, e.g., FileInputStream
long byteCount;  // size of input stream

InputStreamContent mediaContent = new InputStreamContent("application/octet-stream", inputStream);
// Knowing the stream length allows server-side optimization, and client-side progress
// reporting with a MediaHttpUploaderProgressListener.
mediaContent.setLength(byteCount);

StorageObject objectMetadata = null;

if (useCustomMetadata) {
  // If you have custom settings for metadata on the object you want to set
  // then you can allocate a StorageObject and set the values here. You can
  // leave out setBucket(), since the bucket is in the insert command's
  // parameters.
  objectMetadata = new StorageObject()
      .setName("myobject")
      .setMetadata(ImmutableMap.of("key1", "value1", "key2", "value2"))
      .setAcl(ImmutableList.of(
          new ObjectAccessControl().setEntity("domain-example.com").setRole("READER"),
          new ObjectAccessControl().setEntity("user-administrator@example.com").setRole("OWNER")
          ))
      .setContentDisposition("attachment");
}

Storage.Objects.Insert insertObject = storage.objects().insert("mybucket", objectMetadata,
    mediaContent);

if (!useCustomMetadata) {
  // If you don't provide metadata, you will have specify the object
  // name by parameter. You will probably also want to ensure that your
  // default object ACLs (a bucket property) are set appropriately:
  // https://developers.google.com/storage/docs/json_api/v1/buckets#defaultObjectAcl
  insertObject.setName("myobject");
}

// For small files, you may wish to call setDirectUploadEnabled(true), to
// reduce the number of HTTP requests made to the server.
if (mediaContent.getLength() > 0 && mediaContent.getLength() <= 2 * 1000 * 1000 /* 2MB */) {
  insertObject.getMediaHttpUploader().setDirectUploadEnabled(true);
}

insertObject.execute();

The recommended way to use Google Cloud Storage from Java is to use the Cloud Storage Client Libraries .从 Java 使用 Google Cloud Storage 的推荐方法是使用Cloud Storage Client Libraries

The GitHub page for this client gives several examples and resources to learn how to use it properly. 此客户端GitHub 页面提供了几个示例和资源,以了解如何正确使用它。

It also gives this code sample as an example of how to upload objects to Google Cloud Storage using the client library:它还提供此代码示例作为如何使用客户端库将对象上传到 Google Cloud Storage 的示例:

import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;

// Create your service object
Storage storage = StorageOptions.getDefaultInstance().getService();

// Create a bucket
String bucketName = "my_unique_bucket"; // Change this to something unique
Bucket bucket = storage.create(BucketInfo.of(bucketName));

// Upload a blob to the newly created bucket
BlobId blobId = BlobId.of(bucketName, "my_blob_name");
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, "a simple blob".getBytes(UTF_8));

I also tried with using GCS, but it did not worked for me.我也尝试过使用 GCS,但它对我不起作用。 Finally, I did with using ServletFileUpload class.最后,我使用了 ServletFileUpload 类。 Below is the code that I wrote in order to create Google Bucket and to upload the file selected by the user, to that Bucket:下面是我为了创建 Google Bucket 并将用户选择的文件上传到该 Bucket 而编写的代码:

package com1.KT1;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;


public class TestBucket extends HttpServlet {
    private static final long serialVersionUID = 1L;


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // Instantiates a client
        String targetFileStr ="";
        List<FileItem> fileName = null;
        Storage storage = StorageOptions.getDefaultInstance().getService();

        // The name for the new bucket
        String bucketName = "vendor-bucket13";  // "my-new-bucket";

        // Creates the new bucket
        Bucket bucket = storage.create(BucketInfo.of(bucketName));


        //Object requestedFile = request.getParameter("filename");


        ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
        try {
             fileName = sfu.parseRequest(request);
             for(FileItem f:fileName)
                {
                try {
                    f.write (new File("/Users/tkmajdt/Documents/workspace/File1POC1/" + f.getName()));
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                //targetFileStr = readFile("/Users/tkmajdt/Documents/workspace/File1POC1/" + f.getName(),Charset.defaultCharset());
                targetFileStr = new String(Files.readAllBytes(Paths.get("/Users/tkmajdt/Documents/workspace/File1POC1/" + f.getName())));
                }
        } 

    //response.getWriter().print("File Uploaded Successfully");


//String content = readFile("test.txt", Charset.defaultCharset());

        catch (FileUploadException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



        /*if(requestedFile==null)
        {
            response.getWriter().print("File Not Found");
        }*/
        /*else
        {
            //String fileName = (String)requestedFile;
            FileInputStream fisTargetFile = new FileInputStream(fileName);

            targetFileStr = IOUtils.toString(fisTargetFile, "UTF-8");
        }*/



        BlobId blobId = BlobId.of(bucketName, "my_blob_name");
        //Blob blob = bucket.create("my_blob_name", "a simple blob".getBytes("UTF-8"), "text/plain");
        Blob blob = bucket.create("my_blob_name", targetFileStr.getBytes("UTF-8"), "text/plain");

        //storage.delete("vendor-bucket3");
    }




}

I uploaded the whole source code to GitHub我将整个源代码上传到 GitHub

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

相关问题 Google Cloud Storage使用Java上传文件 - Google Cloud Storage upload a file using java 如何在java中逐行上传文件到谷歌云存储 - how to upload file line by line to google cloud storage in java 将文件上传到 Google Cloud Storage (Java) - Upload a file to Google Cloud Storage (Java) 上传文件到谷歌云存储(JAVA) - Upload file to google cloud storage (JAVA) 如何使用Java将图像/视频上传到Google Cloud Storage - How to Upload Image/Videos to Google Cloud Storage Using Java 如何使用Java API将超过32Mb的文件上传到谷歌云存储 - How to upload a file more that 32Mb to google cloud storage using Java API 如何使用Java App Engine正确上传(映像)文件到Google云端存储? - How to properly upload (image) file to Google Cloud Storage using Java App Engine? 如何使用Ajax,Java,Spring Framework将文件从网页上传到Google Cloud Storage - How to upload a file from webpage to Google Cloud Storage using Ajax, Java, Spring Framework 通过Servlet将文件从HTML表格上传到Google云端存储(使用Google Cloud Storage Client Library for Java) - Upload file from HTML form through Servlet to Google Cloud Storage (using Google Cloud Storage Client Library for Java) 通过Google App Engine(Java)将文件上传到Google云端存储 - Upload file to Google cloud storage from Google App Engine (Java)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM