Error in upload and download file in spring boot rest api

Viewed 35

Error creating bean with name 'fileController': Unsatisfied dependency expressed through field 'fileStorageService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStorageService' defined in file [C:\Users\coral\Documents\fileUploadAndDownloadAPI\file-demo\target\classes\com\example\filedemo\filedemo\service\FileStorageService.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.filedemo.filedemo.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException 2022-09-06 15:10:59.300 INFO 17436 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat] 2022-09-06 15:10:59.338 INFO 17436 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2022-09-06 15:10:59.393 ERROR 17436 --- [ main] o.s.boot.SpringApplication : Application run failed org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'fileController': Unsatisfied dependency expressed through field 'fileStorageService'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStorageService' defined in file [C:\Users\coral\Documents\fileUploadAndDownloadAPI\file-demo\target\classes\com\example\filedemo\filedemo\service\FileStorageService.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.filedemo.filedemo.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:659) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:639) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:119) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:399) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1431) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:619) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.22.jar:5.3.22]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:955) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.22.jar:5.3.22] at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.22.jar:5.3.22]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:147) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:734) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:408) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1306) ~[spring-boot-2.7.3.jar:2.7.3] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1295) ~[spring-boot-2.7.3.jar:2.7.3] at com.example.filedemo.filedemo.FileDemoApplication.main(FileDemoApplication.java:17) ~[classes/:na] Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStorageService' defined in file [C:\Users\coral\Documents\fileUploadAndDownloadAPI\file-demo\target\classes\com\example\filedemo\filedemo\service\FileStorageService.class]: Bean instantiation via constructor failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.filedemo.filedemo.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:315) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:296) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1372) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1222) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:542) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.22.jar:5.3.22]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:276) ~[spring-beans-5.3.22.jar:5.3.22]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1391) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1311) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.resolveFieldValue(AutowiredAnnotationBeanPostProcessor.java:656) ~[spring-beans-5.3.22.jar:5.3.22] ... 20 common frames omitted Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.example.filedemo.filedemo.service.FileStorageService]: Constructor threw exception; nested exception is java.lang.NullPointerException at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:224) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:117) ~[spring-beans-5.3.22.jar:5.3.22] at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:311) ~[spring-beans-5.3.22.jar:5.3.22] ... 33 common frames omitted Caused by: java.lang.NullPointerException: null at java.base/java.util.Objects.requireNonNull(Unknown Source) ~[na:na] at java.base/sun.nio.fs.WindowsFileSystem.getPath(Unknown Source) ~[na:na] at java.base/java.nio.file.Path.of(Unknown Source) ~[na:na] at java.base/java.nio.file.Paths.get(Unknown Source) ~[na:na] at com.example.filedemo.filedemo.service.FileStorageService.(FileStorageService.java:30) ~[classes/:na] at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:na] at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source) ~[na:na] at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source) ~[na:na] at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Unknown Source) ~[na:na]

- List item ---------

   at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source)    ~[na:na]
   at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:211)    ~[spring-beans-5.3.22.jar:5.3.22]
   ... 35 common frames omitted
  1. Controller package com.example.filedemo.filedemo.controller; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.io.Resource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.support.ServletUriComponentsBuilder; import com.example.filedemo.filedemo.payload.UploadFileResponse; import com.example.filedemo.filedemo.service.FileStorageService;

    @RestController public class FileController {
    

    private static final Logger logger = LoggerFactory.getLogger(FileController.class); @Autowired private FileStorageService fileStorageService; @PostMapping("/uploadFile") public UploadFileResponse uploadFile(@RequestParam("file") MultipartFile file){ String fileName = fileStorageService.storeFile(file);

    String fileDownloadUri = ServletUriComponentsBuilder.fromCurrentContextPath().path("/dowloadFile/").path(fileName).toUriString();
    
    return new UploadFileResponse(fileName, fileDownloadUri, file.getContentType(),file.getSize());    }
    
    @PostMapping("/uploadMultipleFiles")    public List<UploadFileResponse> uploadMultipleFiles(@RequestParam("files")MultipartFile files)    {
    return Arrays.asList(files).stream().map(file -> uploadFile(file)).collect(Collectors.toList());    }
    
    @GetMapping("/downloadFile/{fileName:.+}")    public ResponseEntity<Resource> downloadFile(@PathVariable String fileName, HttpServletRequest request) {
    // Load file as Resource
    Resource resource = fileStorageService.loadFileAsResource(fileName);
    
    // Try to determine file's content type
    String contentType = null;
    try {
        contentType = request.getServletContext().getMimeType(resource.getFile().getAbsolutePath());
    } catch (IOException ex) {
        logger.info("Could not determine file type.");
    }
    
    // Fallback to the default content type if type could not be determined
    if(contentType == null) {
        contentType = "application/octet-stream";
    }
    
    return ResponseEntity.ok()
            .contentType(MediaType.parseMediaType(contentType))
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
            .body(resource);    }
    }
    
  2. Service package com.example.filedemo.filedemo.service; import java.io.IOException; import java.net.MalformedURLException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption;

    import org.springframework.beans.factory.annotation.Autowired; import    org.springframework.core.io.Resource; import    org.springframework.core.io.UrlResource; import    org.springframework.stereotype.Service; import    org.springframework.util.StringUtils; import    org.springframework.web.multipart.MultipartFile;
    import com.example.filedemo.filedemo.exception.FileStorageException;    import    com.example.filedemo.filedemo.exception.MyFileNotFoundException;    import com.example.filedemo.filedemo.property.FileStorageProperties;
    @Service public class FileStorageService {
    private final Path fileStorageLocation;
    @Autowired public FileStorageService(FileStorageProperties    fileStorageProperties){    this.fileStorageLocation = Paths.get(fileStorageProperties.getUploadDir())
        .toAbsolutePath().normalize();
    try{
    Files.createDirectories(this.fileStorageLocation);    } catch (Exception ex){
    throw new FileStorageException("Could not create the directory where the uploaded files will be stored.",ex);    }  }
    

    public String storeFile(MultipartFile file){ String fileName = StringUtils.cleanPath(file.getOriginalFilename()); try { if(fileName.contains("..")){ throw new FileStorageException("Sorry!!Invalid Path" + fileName); } Path targetLocation = this.fileStorageLocation.resolve(fileName); Files.copy(file.getInputStream(),targetLocation,StandardCopyOption.REPLACE_EXISTING);

    return fileName;    } catch(IOException ex){
    throw new FileStorageException("Could not store file"+fileName+".Please try again!", ex);
    }  }
    

    public Resource loadFileAsResource(String fileName){ try { Path filePath = this.fileStorageLocation.resolve(fileName).normalize();

    Resource resource = new UrlResource(filePath.toUri());
    
    if(resource.exists()) {
        return resource;
    } else {
        throw new MyFileNotFoundException("File not found " + fileName);
    }    } catch (MalformedURLException ex) {
    throw new MyFileNotFoundException("File not found " + fileName, ex);    } } }
    
0 Answers
Related