春季:参考资源/静态文件夹 [英] Spring: refering the resources/static folder

查看:42
本文介绍了春季:参考资源/静态文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在客户端使用Spring Boot和AngularJS开发Rest API,我正在使用下面的RestController在Spring中将文件上传到/resources/static/upload,并在客户端使用它们

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

}

这是我访问上传的图像"image.jpg"的方式

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

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

但是,当我运行mvn软件包并启动我的应用程序jar文件时,无法在客户端访问上载的图像,找不到404.

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.

有人可以解释一下Spring如何存储和引用静态资源,以及如何解决这个问题.

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

推荐答案

我正在使用目录的绝对路径,这在两种情况下都有效:当它与mvn spring-boot:run一起运行时以及当它与java -jar app.jar一起运行时.

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.

例如,您可以尝试将上传内容保存到/opt/upload(确保它存在并且用户有权写入它):

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

此外,您还应该将Spring配置为提供从该目录上传的内容:

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

}

有关配置资源处理程序的更多信息: http://www.baeldung.com/spring -mvc-static-resources

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

这篇关于春季:参考资源/静态文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆