I am a beginner using Spring MVC , i am developing a social network android application. The user should have the ability to upload posts in news feed.
The each post can have maximum one image attached , so i need to store image files on server.
I have already implemented an example of the upload process using RestTemplate :
FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter();
formHttpMessageConverter.setCharset(Charset.forName("UTF8"));
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add( formHttpMessageConverter );
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file", new FileSystemResource(path)); /* path - is the path of the
image i want to upload */
map.add("username","user1");
HttpHeaders imageHeaders = new HttpHeaders();
imageHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
HttpEntity<MultiValueMap<String, Object>> imageEntity = new HttpEntity<>(map, imageHeaders);
restTemplate.exchange(messageURL, HttpMethod.POST, imageEntity, Boolean.class);
And on the Spring MVC side :
@RequestMapping(value = "/uploadPhoto/{id}", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<String> uploadPhoto(@RequestParam("file") MultipartFile srcFile,
@PathVariable("id") Integer id,
@RequestParam("username") String username)
{
System.out.println("Photo name = "+srcFile.getName());
System.out.println("Photo size = "+srcFile.getSize());
System.out.println("Photo original name = "+srcFile.getOriginalFilename());
System.out.println("Username = "+username);
String uploadsDir = "/uploads/";
String realPathtoUploads = context.getRealPath(uploadsDir);
if(! new File(realPathtoUploads).exists())
{
new File(realPathtoUploads).mkdir();
}
String orgName = srcFile.getOriginalFilename();
String filePath = realPathtoUploads + orgName;
File dest = new File(filePath);
try
{
srcFile.transferTo(dest);
}
catch (IllegalStateException | IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
This code works, using it i can upload a photo from the phone storage to the server, but, the problem is that i want to get the URL for the uploaded photo, in order to save it on database and to be able to download it in the future, how can i do that ?
Aucun commentaire:
Enregistrer un commentaire