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

标签 java eclipse file-upload google-cloud-platform google-cloud-storage

我一直在尝试使用我的应用程序在 Google Cloud Storage 上上传 pdf 文件,但无法执行此操作。我在网上搜索并找到了下面给出的代码,但问题是该代码在上传 txt 时很有用文件,但不是 pdf 文件。当我尝试上传 pdf 文件时,它上传成功,但当我尝试打开它时,它无法打开。我使用以下代码:

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

有人可以帮忙解决这个问题吗。
预先感谢您

最佳答案

我使用以下代码解决了该问题:

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,"application/pdf");而不是
Blob blob=bucket.create(fileName+""+date.toString(),fileInputStream,"text/plain");

关于java - 如何使用 Java 在 Google Cloud Storage 中插入 pdf 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51710723/

相关文章:

java - eclipse 不验证 struts.xml 文件

java - 无法在 eclipse mars 中更改动态 Web 模块 3.1

java - 从命令行运行时,Eclipse 的 Java 编译器会生成不同的堆栈跟踪

java - 使用jsp仅上传特定类型的文件

java - JSP:如何使用 onClick 或 onSubmit 事件在列表中添加值?

Java如何从2D数组获取1D数组引用

java - 尝试执行脚本时,Runtime.exec() 会出现 java 问题,但某些命令可以工作

javascript - 蒸发JS : Always get 403 SignatureDoesNotMatch error after resuming an upload

php - Laravel - 文件需要验证反之亦然

java - vert.x 中事件总线的大小