How to upload Manytoone entity relationship and save to database?

Asked

Viewed 45 times

0

How do I upload (Multipartfile) with Manytoone relationship, in my case I want to upload image in a Call(Entity). Follow the code below:

@Entity
@DynamicUpdate
public class FileInfo {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;
  private String filename;  
  private String url;
  @ManyToOne
  @JoinColumn(name = "chamado_id")
  private Chamado chamado;
  @Lob
  private byte[] data;


  public FileInfo(Long id, String filename, String url, Chamado chamado, byte[] data) {

    this.id = id;
    this.filename = filename;
    this.url = url;
    this.chamado = chamado;
    this.data = data;
}

Service class

@Override
public void salvar(MultipartFile file){
     String fileName = StringUtils.cleanPath(file.getOriginalFilename());

    try {
        Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
        FileInfo fileInfo = new FileInfo(null, fileName, file.getContentType(), null, file.getBytes());

        fileStorageRepository.save(fileInfo);
    } catch (Exception e) {
        throw new RuntimeException("FAIL! -> message = " + e.getMessage());
    }
}

Controller

@RequestMapping(value = "/novo", method = RequestMethod.POST)
public ModelAndView  salvar(@Validated @ModelAttribute("chamado") Chamado chamado, BindingResult result, RedirectAttributes attributes,
        @RequestParam("uploadfile") MultipartFile file, Model model) {

    if(result.hasErrors()){
         return novo(chamado);
    }

    try {
        chamado.setStatus(Status.NOVO);

        fileStorage.salvar(file); // Salva 
        model.addAttribute("message", "File uploaded successfully! -> filename = " + file.getOriginalFilename());
        chamadoService.salvar(chamado);

        attributes.addFlashAttribute("mensagem", "Ticket salvo com sucesso!");
        return new ModelAndView("redirect:/tickets/novo"); 

    } catch (NumberFormatException e) {
        model.addAttribute("message", "Fail! -> uploaded filename: " + file.getOriginalFilename());
        ModelAndView mv = new ModelAndView(CADASTRO_VIEW);
        result.addError(new ObjectError("error", e.getMessage()));
        return mv;

    }   
}
  • Day Claudino, good morning, please, instead of prints put only the code to facilitate

  • All right, I’ll edit.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.