Reputation: 1582
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.
Upvotes: 1
Views: 16895
Reputation: 838
First of all you cannot store in the folder structure you see in your IDE that is not how your code will be in a deployed package
File convFile = new File("src/main/resources/static/upload/"+file.getOriginalFilename());
store using relative path
File convFile = new File("/static/upload/"+file.getOriginalFilename());
and also add the resource location mapping in spring config for your image upload folder .
<mvc:resources mapping="/upload/**" location="/static/upload/" />
Upvotes: 0
Reputation: 15204
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
Upvotes: 3