简体   繁体   English

upload image using angular and spring boot into postgres

[英]upload image using angular and spring boot into postgres

I'm trying to upload image into database sql, at first i add column into database called photo and the data type is varchar(100) then in post contrller i do this :

@PostMapping("/save")
public ResponseEntity<Invoice> addInvoice(@RequestBody InvoiceDTO invoice , @RequestParam("image") MultipartFile multipartFile) throws IOException {

    String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
    invoice.setPhoto(fileName);
    Invoice savedInvoice = invoiceService.saveInvoice(invoice);
    String uploadDir = "user-photos/" + savedInvoice.getId();
    FileUpload.saveFile(uploadDir, fileName, multipartFile);
    LOGGER.info(" invoice saved  " + invoice.getSerialNumber() + "and id : " + invoice.getId());
    return new ResponseEntity<>(savedInvoice, HttpStatus.CREATED);

}

and i create FileUpload class to and this is what it's contains :

public class FileUpload
{
    public static void saveFile(String uploadDir, String fileName,
                                                    MultipartFile multipartFile) throws IOException {
    Path uploadPath = Paths.get(uploadDir);

    if (!Files.exists(uploadPath)) {
        Files.createDirectories(uploadPath);
    }

    try (InputStream inputStream = multipartFile.getInputStream()) {
        Path filePath = uploadPath.resolve(fileName);
        Files.copy(inputStream, filePath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException ioe) {
        throw new IOException("Could not save image file: " + fileName, ioe);
    }
}
}

and in angular form i do this :

<div class="addreq">
  <form class="form" [formGroup]="addstudentform" enctype="multipart/form-data" >
    <h1 class ="header" > Add new invoice </h1>

    <input formControlName="serialNumber" type="number" placeholder=" serialNumber "><br>
    <input formControlName="status" type="text" placeholder=" status"><br>
    <input formControlName="customerSerialNumber" type="text" placeholder="customer serial number"><br>
    <input formControlName="employeeSerialNumber" type="text" placeholder="employee serial number"><br>
    <input type="file" name="image" accept="image/png, image/jpeg" />

    <button  (click)="onSave()" type="submit" class="main-btn"> Save</button>

  </form>

</div>

and this is my typescript :

export class AddInvoiceComponent implements OnInit {


  addstudentform: FormGroup = this._formbuilder.group({
    serialNumber: ['', Validators.required],
    status: ['', Validators.required],
    customerSerialNumber: ['', Validators.required],
    employeeSerialNumber: ['', Validators.required],

});

constructor(private _formbuilder: FormBuilder,
    private _http: HttpClient
) { }

ngOnInit(): void { }

onSave(): void {

    let serialNumber = this.addstudentform.get('serialNumber')?.value;
    let status = this.addstudentform.get('status')?.value;
    let customerSerialNumber =this.addstudentform.get('customerSerialNumber')?.value;
    let employeeSerialNumber = this.addstudentform.get('employeeSerialNumber')?.value;


    let body = {
      serialNumber: serialNumber,
      status: status,
      customerSerialNumber: customerSerialNumber,
      employeeSerialNumber: employeeSerialNumber
    }
    console.warn(body);

    this._http.post("http://localhost:8085/invoice/save", body).subscribe()


}
}

and all of this not working and return error:

error: "Internal Server Error" message: "Current request is not a multipart request"

help please..

The 'save' endpoint expects a form to be posted in the request and in your Angular component you send JSON data. “保存”端点希望在请求中发布一个表单,并且在您发送 JSON 数据的 Angular 组件中。 What you have to do is update your Angular component and send a multipart request by using FormData :您需要做的是更新您的 Angular 组件并使用FormData发送多部分请求:

 var formData:any = new FormData(); formData.append("serialNumber",this.addstudentform.get('serialNumber')?.value); formData.append("status",this.addstudentform.get('status')?.value); formData.append("customerSerialNumber",this.addstudentform.get('customerSerialNumber')?.value); formData.append("employeeSerialNumber",this.addstudentform.get('employeeSerialNumber')?.value); formData.append("photo",this.addstudentform.get('photo')?.value); this._http.post("http://localhost:8085/invoice/save", formData).subscribe()

and in your HTML you have to change:在您的 HTML 中,您必须更改:

 <input formControlName="photo" type="file" name="image" accept="image/png, image/jpeg" />

using multipart request as described in the answer you'll also need to modify the controller method according to the form params.使用答案中描述的多部分请求,您还需要根据表单参数修改 controller 方法。

 addInvoice(@RequestParam(name='serialNumber') String serialNumber, @RequestParam(name='status') String status, /** add other params... */ @RequestPart(name='photo') MultipartFile photo) throws IOException { }

https://www.baeldung.com/sprint-boot-multipart-requests https://www.baeldung.com/sprint-boot-multipart-requests

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM