Spring:引用资源/静态文件夹 [英] Spring: refering the resources/static folder

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

问题描述

我正在客户端使用 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 package 并启动我的应用程序 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-静态资源

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

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

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