Save Image to Google Cloud Storage

I am currently working on a project where we should be able to upload files to google cloud storage. So we've created a Bucket, and I've added a Maven dependency to my local "normal" application:

<dependencies>
    <dependency>
        <groupId>com.google.appengine.tools</groupId>
        <artifactId>appengine-gcs-client</artifactId>
        <version>RELEASE</version>
    </dependency>
</dependencies>

      

Then I started reading the local file and tried to transfer it to Google Cloud storage simply:

try {
    final GcsService gcsService = GcsServiceFactory
        .createGcsService();

    File file = new File("/tmp/test.jpg");
    FileInputStream fis = new FileInputStream(file);
    GcsFilename fileName = new GcsFilename("test1213","test.jpg");
    GcsOutputChannel outputChannel;
    outputChannel = gcsService.createOrReplace(fileName, GcsFileOptions.getDefaultInstance());
    copy(fis, Channels.newOutputStream(outputChannel));
} catch (IOException e) {
    e.printStackTrace();
}

      

My method copy

looks like this:

private static final int BUFFER_SIZE = 2 * 1024 * 1024;

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

      

All I get from this is:

The API package 'file' or call 'Create()' was not found.

      

After searching a lot on google, reading the documentation, even searching in bing, I found this entry: API Packages 'package' or 'CreateChannel ()' call was not found

It says there is no such use appengine.tools -> gcs-client

without such an AppEngine. But is there an easy way to upload files to Google Cloud Storage without being forced to use the AppEngine service?

+3


source to share


2 answers


It looks like you are not using App Engine. This is completely normal. Google Cloud Storage can work fine with App Engine, but it doesn't require it. The appengine-gcs-client package you are trying to use requires App Engine.

Instead you want google-api-services-storage.



Here's an example using the GCS JSON API with Java and Maven here:

https://cloud.google.com/storage/docs/json_api/v1/json-api-java-samples

+3


source


Here is the code for my APP Engine servlet that returns data and a photo and then stores it in the datastore and cloud storage. Hope this helps you.



@Override
          public void doPost(HttpServletRequest req, HttpServletResponse res)
              throws ServletException, IOException {            

            //Get GCS service
            GcsService gcsService = GcsServiceFactory.createGcsService();

            //Generate string for my photo
            String unique = UUID.randomUUID().toString();     

            //Open GCS File
            GcsFilename filename = new GcsFilename(CONSTANTES.BUCKETNAME, unique+".jpg");               

            //Set Option for that file
            GcsFileOptions options = new GcsFileOptions.Builder()
                    .mimeType("image/jpg")
                    .acl("public-read")
                    .build();


            //Canal to write on it
            GcsOutputChannel writeChannel = gcsService.createOrReplace(filename, options);

            //For multipart support
            ServletFileUpload upload = new ServletFileUpload(); 

            //Trying to create file   
            try {


                FileItemIterator iterator = upload.getItemIterator(req);


                    while (iterator.hasNext()) {
                        FileItemStream item = iterator.next();                      
                        InputStream stream = item.openStream();

                        if (item.isFormField()) {                       

                          String texte_recu_filtre = IOUtils.toString(stream);                       

                          if (item.getFieldName().equals("Type")){
                              Type=Integer.parseInt(texte_recu_filtre);                           
                          }else if (item.getFieldName().equals("DateHeure")){
                              DateHeure=texte_recu_filtre;
                          }else if (item.getFieldName().equals("NumPort")){
                              NumPort=texte_recu_filtre;
                          }else if (item.getFieldName().equals("CodePays")){
                              CodePays=Integer.parseInt(texte_recu_filtre);
                          }

                        } else {                    


                          byte[] bytes = ByteStreams.toByteArray(stream);

                          try {
                                //Write data from photo
                                writeChannel.write(ByteBuffer.wrap(bytes));                             

                          } finally {                             

                                writeChannel.close();
                                stream.close();

                                /
                                res.setStatus(HttpServletResponse.SC_CREATED);

                                res.setContentType("text/plain");
                          }        
                        }        
                  }



                Key<Utilisateur> cleUtilisateur = Key.create(Utilisateur.class, NumPort);               


                Utilisateur posteur = ofy().load().key(cleUtilisateur).now();               

                //Add to datatstore with Objectify
                Campagne photo_uploaded = new Campagne(CONSTANTES.chaineToDelete+unique+".jpg", Type, date_prise_photo, 0, cleUtilisateur, CodePays, posteur.getliste_contact());

                ofy().save().entity(photo_uploaded).now();                          


                } catch (FileUploadException e) {

                    e.printStackTrace();
                }               

         } 

      

+3


source







All Articles