Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

java - Spring: refering the resources/static folder

I am developing a Rest API using Spring Boot and AngularJS in the client side, i am uploading files to /resources/static/upload with Spring using the RestController below and using them in the client side

@RestController
@CrossOrigin("*")
public class FilmController {
    @Autowired
    private FilmRepository filmRepository;

    @RequestMapping(value = "/films", method = RequestMethod.POST)
    public void saveFilm(@RequestParam("file") MultipartFile file) throws Exception {

        File convFile = new File("src/main/resources/static/upload/"+file.getOriginalFilename());

        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        Blob blob = new SerialBlob(file.getBytes());

        fos.write(file.getBytes());
        fos.close();
        System.out.println(convFile.getName());


        filmRepository.save(new Film(convFile.getName(), blob));
    }

    @RequestMapping(value = "/films", method = RequestMethod.GET)
    public List<Film> getAllFilms() {
        return filmRepository.findAll();
    }

}

Here is how i accessed the uploaded image "image.jpg"

<img src="http://localhost:8080/upload/image.jpg" />

But, when i ran mvn package and i launch my application jar file, i can't access the uploaded image in the client side, i get 404 not found.

Can someone explain how Spring store and refer to static resources and how can i resolve this problem.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I'm using absolute path to the directory and this works in both cases: when it's runing with mvn spring-boot:run and when it's running as java -jar app.jar.

For example, you could try to save uploads to /opt/upload (make sure that it exists and user has permissions to write into it):

File convFile = new File("/opt/upload/"+file.getOriginalFilename());

Also you should configure Spring to serve uploads from this directory:

@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/upload/**")
          .addResourceLocations("file:/opt/upload/");
    }

}

More info about configuring resource handler: http://www.baeldung.com/spring-mvc-static-resources


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...