Reputation: 3571
I'm new to Spring-Boot,i'm trying to upload file to Mongodb Database, save its objectId and link it to my document, in order to download it Later. Here is my class Person:
@Document
public class Person {
@Id
private String id;
private String firstName;
private String lastName;
private String age;
private String filename;
private ObjectId file;
....}
This is my controller method:
@RequestMapping(value="/addperson",method=RequestMethod.POST)
public String ajout(Model model,@Valid PersonForm pf){
Person p=new Person(pf.getFirstname(),pf.getLastName(),pf.getAge());
InputStream inputStream=null;
try {
inputStream = new FileInputStream("E:/usb/");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
p.setFilename(pf.getFilename());
repository.linkFileToMyDoc(p,inputStream,p.getFilename());
repository.save(p);
model.addAttribute("PersonForm",pf);
return "personview";
}
I wonder if it is the best method to do it. the error i get is that access to "E:/usb/" is denied. Can anyone help please
Upvotes: 1
Views: 2495
Reputation: 3571
i found the solution after reading MultipartFile documentation. I uploaded file to server and then transfered it to directory,after allowing total control to directory "E:/usb/". this is my controller method:
Person p=new Person(pf.getFirstname(),pf.getLastName(),pf.getAge());
try {
File dest = null;
String str = "C:/tt/"+pf.getFile().getOriginalFilename();
File dir = new File(str);
dir.createNewFile();
pf.getFile().transferTo(dir);
p.setFilename(str);
InputStream inputStream=pf.getFile().getInputStream();
repository.linkFileToMyDoc(p,inputStream,pf.getFile().getOriginalFilename());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repository.save(p);
model.addAttribute("PersonForm",pf);
return "personview";
}
the linkFileToMydoc method, you'll find it in this link: How to reference GridFSFile with @DbRef annotation (spring data mongodb)
Upvotes: 1