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 >
<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" > 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..
CodePudding user response:
The 'save' endpoint expects a form to be posted in the request and in your Angular component you send JSON data. What you have to do is update your Angular component and send a multipart request by using 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:
<input formControlName="photo" type="file" name="image" accept="image/png, image/jpeg" />
CodePudding user response:
using multipart request as described in the answer you'll also need to modify the controller method according to the form params.
addInvoice(@RequestParam(name='serialNumber') String serialNumber,
@RequestParam(name='status') String status,
/** add other params... */
@RequestPart(name='photo') MultipartFile photo) throws IOException {
}