2
votes

I want to upload images to google cloud storage and here is my code from spring boot. But the problem is this isnt working at all giving me error like this:

2018-10-22 15:22:55.628 ERROR 6172 --- [nio-8080-exec-6] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.IllegalArgumentException: Invoked method public abstract java.io.InputStream org.apache.commons.fileupload.FileItemStream.openStream() throws java.io.IOException is no accessor method!] with root cause

please help me. following is the code i wrote

 private static Storage storage = null;

    // [START init]
    static {
        storage = StorageOptions.getDefaultInstance().getService();
    }

 @SuppressWarnings("deprecation")
 @RequestMapping(method = RequestMethod.POST, value = "/imageUpload")
 public String uploadFile(FileItemStream fileStream)
        throws IOException, ServletException {

     String bucketName = "mcqimages";
        checkFileExtension(fileStream.getName());
        DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
        DateTime dt = DateTime.now(DateTimeZone.UTC);
        String dtString = dt.toString(dtf);
        final String fileName = fileStream.getName() + dtString;


        BlobInfo blobInfo =
                storage.create(
                        BlobInfo
                        .newBuilder(bucketName, fileName)
                        .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
                        .build(),
                        fileStream.openStream());

        return blobInfo.getMediaLink();
    }

    private void checkFileExtension(String fileName) throws ServletException {
        if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
            String[] allowedExt = {".jpg", ".jpeg", ".png", ".gif"};
            for (String ext : allowedExt) {
                if (fileName.endsWith(ext)) {
                    return;
                }
            }
            throw new ServletException("file must be an image");
        }
    }
2

2 Answers

2
votes

finally i came up with this code :). worked very well. need the Credentials to upload files into GCP storage. you can generate the credentials from JSON format too.

https://cloud.google.com/docs/authentication/production

     Credentials credentials = GoogleCredentials.fromStream(new FileInputStream("C:\\Users\\sachinthah\\Downloads\\MCQ project -1f959c1fc3a4.json"));

Storage storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

            public CloudStorageHelper() throws IOException {
            }


            @SuppressWarnings("deprecation")
            @RequestMapping(method = RequestMethod.POST, value = "/imageUpload112")
            public String uploadFile(@RequestParam("fileseee")MultipartFile fileStream)
                    throws IOException, ServletException {

                String bucketName = "mcqimages";
                checkFileExtension(fileStream.getName());
                DateTimeFormatter dtf = DateTimeFormat.forPattern("-YYYY-MM-dd-HHmmssSSS");
                DateTime dt = DateTime.now(DateTimeZone.UTC);
                String dtString = dt.toString(dtf);
                final String fileName = fileStream.getName() + dtString;

                File file = convertMultiPartToFile( fileStream );

                BlobInfo blobInfo =
                        storage.create(
                                BlobInfo
                                        .newBuilder(bucketName, fileName)
                                        .setAcl(new ArrayList<>(Arrays.asList(Acl.of(User.ofAllUsers(), Role.READER))))
                                        .build()
        //                     file.openStream() 
        );
                System.out.println(blobInfo.getMediaLink());
                return blobInfo.getMediaLink();
            }


            private File convertMultiPartToFile(MultipartFile file ) throws IOException
            {
                File convFile = new File( file.getOriginalFilename() );
                FileOutputStream fos = new FileOutputStream( convFile );
                fos.write( file.getBytes() );
                fos.close();
                return convFile;
            }


            private void checkFileExtension(String fileName) throws ServletException {
                if (fileName != null && !fileName.isEmpty() && fileName.contains(".")) {
                    String[] allowedExt = {".jpg", ".jpeg", ".png", ".gif"};
                    for (String ext : allowedExt) {
                        if (fileName.endsWith(ext)) {
                            return;
                        }
                    }
                    throw new ServletException("file must be an image");
                }
            }
1
votes

I would try to upload the file instead:

public String uploadFile(@RequestParam("file") MultipartFile file) {
    if (file.isEmpty()) {
        //Set error message
    }
    else {
        try {
            String extension = FilenameUtils.getExtension(file.getOriginalFilename()); //Commons IO

            // Get the file 
            byte[] bytes = file.getBytes();
            ....
    }

A good example of uploading files is here: https://www.baeldung.com/spring-file-upload