首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Java在Google Cloud Storage中插入pdf文件

如何使用Java在Google Cloud Storage中插入pdf文件
EN

Stack Overflow用户
提问于 2018-08-06 23:10:42
回答 2查看 1.5K关注 0票数 0

我已经尝试上传一个pdf文件到谷歌云存储使用我的应用程序,但我无法这样做。我已经搜索网络,并找到以下给定的代码,但问题是,这个代码是有用的上传txt文件,但不是pdf file.When我尝试上传它上传成功,但当我试图打开它没有打开它。我使用以下代码:

代码语言:javascript
复制
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
RequestDispatcher rd=req.getRequestDispatcher("career-registration-successfull.jsp");
RequestDispatcher rd1=req.getRequestDispatcher("career-registration-failed.jsp");
String name="";
String email="";
long whatsapp=0;
long number=0;
String query="";
int flag1=0;
int flag2=0;
isMultipart = ServletFileUpload.isMultipartContent(req);
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter( );
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\Subhanshu Bigasia\\Desktop\\Amazon.pdf");
Storage storage = StorageOptions.getDefaultInstance().getService();
Bucket bucket=storage.get(("combucket1eduvitae7"));
ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
String targetFileStr="";
try {
    List<FileItem>  fileName = sfu.parseRequest(req);
     for(FileItem f:fileName)
        {
        try {
            f.write (new File("C:\\Users\\Subhanshu Bigasia\\Desktop\\Afcat.pdf"));
        } 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("C:\\Users\\Subhanshu Bigasia\\Desktop\\Afcat.pdf")));
        }
}
catch(Exception e) {
    e.printStackTrace();
}
BlobId blobId = BlobId.of("combucket1eduvitae", "my_blob_name1");
//Blob blob = bucket.create("my_blob_name1", targetFileStr.getBytes(), "text/plain");
Blob blob=bucket.create("myblob",fileInputStream, "text");

有人能帮忙解决这个问题吗?

提前谢谢你

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-08 04:24:37

我用下面的代码解决了这个问题:

代码语言:javascript
复制
String name="";
String email="";
long whatsapp=0;
long number=0;
String query="";
int flag1=0;
int flag2=0;
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
resp.setContentType("text/html");
java.io.PrintWriter out = resp.getWriter( );
    if( !isMultipart ) {
   out.println("<html>");
   out.println("<head>");
   out.println("<title>Servlet upload</title>");  
   out.println("</head>");
   out.println("<body>");
   out.println("<p>No file uploaded</p>"); 
   out.println("</body>");
   out.println("</html>");
   return;
}

DiskFileItemFactory factory = new DiskFileItemFactory();

// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );

try { 
   // Parse the request to get file items.
   List fileItems = upload.parseRequest(req);

   // Process the uploaded file items
   Iterator i = fileItems.iterator();

   out.println("<html>");
   out.println("<head>");
   out.println("<title>Servlet upload</title>");  
   out.println("</head>");
   out.println("<body>");

   while ( i.hasNext () ) {
      FileItem fi = (FileItem)i.next();
      if ( !fi.isFormField () ) {
         // Get the uploaded file parameters
        try { String fieldName = fi.getFieldName();
         String fileName = fi.getName();
         String contentType = fi.getContentType();
         boolean isInMemory = fi.isInMemory();
         long sizeInBytes = fi.getSize();
         Date date=new Date();             
         System.out.println(("Uploaded Filename: " + fileName + "<br>"));
         flag1=1;
         File f1=new File("C:\\Users\\Subhanshu Bigasia\\Desktop\\amazon2.pdf");
         FileInputStream fileInputStream = (FileInputStream) fi.getInputStream();
         Storage storage = StorageOptions.getDefaultInstance().getService();
         Bucket bucket=storage.get(("combucket1eduvitae7"));
         ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
         BlobId blobId = BlobId.of("combucket1eduvitae", "my_blob_name1");
         //Blob blob = bucket.create("my_blob_name1", targetFileStr.getBytes(), "application/pdf");
         Blob blob=bucket.create(fileName+" "+date.toString(),fileInputStream,"application/pdf");
         flag1=1;
        }
        catch(Exception e) {
            flag1=0;
            e.printStackTrace();
        }
      }

请注意,我使用了

Blob blob=bucket.create(fileName+“"+date.toString(),fileInputStream,”应用程序/pdf“);而不是

Blob blob=bucket.create(fileName+“"+date.toString(),fileInputStream,”文本/纯文本“);

票数 1
EN

Stack Overflow用户

发布于 2018-08-07 19:12:38

首先,遵循Cloud Storage Client Libraries for Java documentation,它将帮助您开始。

然后您可以尝试使用Java (found here)将文件上传到云存储存储桶中:

代码语言:javascript
复制
/**
   * Uploads data to an object in a bucket.
   *
   * @param name the name of the destination object.
   * @param contentType the MIME type of the data.
   * @param file the file to upload.
   * @param bucketName the name of the bucket to create the object in.
   */
  public static void uploadFile(
      String name, String contentType, File file, String bucketName)
      throws IOException, GeneralSecurityException {
    InputStreamContent contentStream = new InputStreamContent(
        contentType, new FileInputStream(file));
    // Setting the length improves upload performance
    contentStream.setLength(file.length());
    StorageObject objectMetadata = new StorageObject()
        // Set the destination object name
        .setName(name)
        // Set the access control list to publicly read-only
        .setAcl(Arrays.asList(
            new ObjectAccessControl().setEntity("allUsers").setRole("READER")));

    // Do the insert
    Storage client = StorageFactory.getService();
    Storage.Objects.Insert insertRequest = client.objects().insert(
        bucketName, objectMetadata, contentStream);

    insertRequest.execute();
  }

您可以在GitHub存储库here中找到简单的入门教程。请同时查看堆栈溢出线程Upload image to Google Cloud Storage (Java)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51710723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档