如何清除UPLOAD组件的MemoryBuffer
How To Clear MemoryBuffer of UPLOAD component
这里是第一个计时器:我有一个上传组件,它可以拍摄图像并将其显示在布局中。保存按钮触发将图像保存到数据库并且工作正常。
问题来了:对于下一条记录,在触发保存方法时,如果上传组件中没有添加图片,则会再次保存之前的图片。(我猜memorybuffer中还有那张图片)。所以我的问题是,如何清除下一条记录的内存缓冲区。另外,我想知道我是否可以检索图像容器中显示的图像以将其保存到图像变量中。
```
public class EmployeeForm extends FormLayout {
Image image;
Button save = new Button("Save");
Button delete = new Button("Delete");
Button close = new Button("Close");
MemoryBuffer buffer= new MemoryBuffer();
Upload upload= new Upload(buffer);
VerticalLayout imageContainer=new VerticalLayout();
BufferedImage inputImageoriginal=null;
public EmployeeForm(List<Office> offices, List<Cell> cells, DbService dbservice) {
binder.bindInstanceFields(this);
office.setItems(dbservice.findOfficesBydistrict());
cell.setItems(dbservice.findCellsBydistrict());
office.setItemLabelGenerator(Office::getOfficeName);
cell.setItemLabelGenerator(Cell::getCellName);
add(firstName, lastName, designation, office, cell, createUpload(), createButtonsLayout(), imageContainer);
}
private Component createUpload() {
upload.setMaxFiles(1);
upload.setMaxFileSize(100000);
upload.setUploadButton(new Button ("Upload Photo"));
upload.setDropLabel(new Label("Drop Photo"));
upload.setAcceptedFileTypes("image/tiff", "image/jpeg", "image/jpg");
upload.addFileRejectedListener(e -> notify.show("Invalid File: Please select only image files less than 100kb",3000, Position.TOP_END));
upload.addSucceededListener(event -> showPicture());
return upload;
}
public void showPicture() {
try {
if (imageContainer != null) {
remove(imageContainer);
}
StreamResource resource = new StreamResource("inputimage",
() -> new ByteArrayInputStream(getImageAsByteArray()));
image = new Image(resource, "No Photo to display");
imageContainer = new VerticalLayout();
imageContainer.setWidth("200px");
imageContainer.setHeight("200px");
imageContainer.getStyle().set("overflow-x", "auto");
imageContainer.add(image);
add(imageContainer);
//imageContainer.get
} catch (Exception e) {
e.printStackTrace();
notify.show("Error" + e);
}
}
public void clearBuffer() {
try {
upload.clearFileList();
} catch (Exception e) {
// TODO: handle exception
}
}
private byte[] getImageAsByteArray() {
try {
inputImageoriginal= ImageIO.read(buffer.getInputStream());
if (inputImageoriginal == null) {
return null;
} else {
BufferedImage inputImage = resizeImage(inputImageoriginal);
ByteArrayOutputStream pngContent = new ByteArrayOutputStream();
ImageIO.write(inputImage, "jpg", pngContent);
InputStream is = new ByteArrayInputStream(pngContent.toByteArray());
return IOUtils.toByteArray(is);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
BufferedImage resizeImage(BufferedImage originalImage) throws IOException {
BufferedImage resizedImage = new BufferedImage(150, 150, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, 150, 150, null);
graphics2D.dispose();
return resizedImage;
}
private Component createButtonsLayout() {
// TODO Auto-generated method stub
save.setWidthFull();
delete.setWidthFull();
close.setWidthFull();
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
save.addClickShortcut(Key.ENTER);
save.addClickListener(event -> validatandSave());
delete.addClickListener(event -> fireEvent(new DeleteEvent(this, employee)));
close.addClickListener(event -> fireEvent(new CloseEvent(this)));
return new HorizontalLayout(save, delete, close);
}
private void validatandSave() {
try {
binder.writeBean(employee);
if (getImageAsByteArray() != null) {
employee.setPicture(getImageAsByteArray());
}
fireEvent(new SaveEvent(this, employee));
} catch (ValidationException e) {
// TODO Auto-generated catch block
Notification notification = Notification.show("Please Enter All Required Fields", 3000,
Position.TOP_CENTER);
}
}
public void setEmployee(Employee employee) {
this.employee = employee;
binder.readBean(employee);
}
///Operation Save/Delete Events
public static abstract class EmployeeFormEvent extends ComponentEvent<EmployeeForm> {
private Employee employee;
protected EmployeeFormEvent(EmployeeForm source, Employee employee) {
super(source, false);
this.employee = employee;
}
public Employee getEmployee() {
return employee;
}
}
public static class SaveEvent extends EmployeeFormEvent {
SaveEvent(EmployeeForm source, Employee employee) {
super(source, employee);
}
}
public static class DeleteEvent extends EmployeeFormEvent {
DeleteEvent(EmployeeForm source, Employee employee) {
super(source, employee);
}
}
public static class CloseEvent extends EmployeeFormEvent {
CloseEvent(EmployeeForm source) {
super(source, null);
}
}
public <T extends ComponentEvent<?>> Registration addListener(Class<T> eventType,
ComponentEventListener<T> listener) {
return getEventBus().addListener(eventType, listener);
}
public void addImage(Image image2) {
// TODO Auto-generated method stub
// remove(imageContainer);
if(imageContainer!=null) {
imageContainer.removeAll();
}
imageContainer.add(image2);
//add(imageContainer);
}
}
```
查看 MemoryBuffer
的实现,您必须将其丢弃并设置一个新的,例如在你的 clearBuffer()
方法中。
buffer = new MemoryBuffer();
upload.setReceiver(buffer);
这里是第一个计时器:我有一个上传组件,它可以拍摄图像并将其显示在布局中。保存按钮触发将图像保存到数据库并且工作正常。
问题来了:对于下一条记录,在触发保存方法时,如果上传组件中没有添加图片,则会再次保存之前的图片。(我猜memorybuffer中还有那张图片)。所以我的问题是,如何清除下一条记录的内存缓冲区。另外,我想知道我是否可以检索图像容器中显示的图像以将其保存到图像变量中。
```
public class EmployeeForm extends FormLayout {
Image image;
Button save = new Button("Save");
Button delete = new Button("Delete");
Button close = new Button("Close");
MemoryBuffer buffer= new MemoryBuffer();
Upload upload= new Upload(buffer);
VerticalLayout imageContainer=new VerticalLayout();
BufferedImage inputImageoriginal=null;
public EmployeeForm(List<Office> offices, List<Cell> cells, DbService dbservice) {
binder.bindInstanceFields(this);
office.setItems(dbservice.findOfficesBydistrict());
cell.setItems(dbservice.findCellsBydistrict());
office.setItemLabelGenerator(Office::getOfficeName);
cell.setItemLabelGenerator(Cell::getCellName);
add(firstName, lastName, designation, office, cell, createUpload(), createButtonsLayout(), imageContainer);
}
private Component createUpload() {
upload.setMaxFiles(1);
upload.setMaxFileSize(100000);
upload.setUploadButton(new Button ("Upload Photo"));
upload.setDropLabel(new Label("Drop Photo"));
upload.setAcceptedFileTypes("image/tiff", "image/jpeg", "image/jpg");
upload.addFileRejectedListener(e -> notify.show("Invalid File: Please select only image files less than 100kb",3000, Position.TOP_END));
upload.addSucceededListener(event -> showPicture());
return upload;
}
public void showPicture() {
try {
if (imageContainer != null) {
remove(imageContainer);
}
StreamResource resource = new StreamResource("inputimage",
() -> new ByteArrayInputStream(getImageAsByteArray()));
image = new Image(resource, "No Photo to display");
imageContainer = new VerticalLayout();
imageContainer.setWidth("200px");
imageContainer.setHeight("200px");
imageContainer.getStyle().set("overflow-x", "auto");
imageContainer.add(image);
add(imageContainer);
//imageContainer.get
} catch (Exception e) {
e.printStackTrace();
notify.show("Error" + e);
}
}
public void clearBuffer() {
try {
upload.clearFileList();
} catch (Exception e) {
// TODO: handle exception
}
}
private byte[] getImageAsByteArray() {
try {
inputImageoriginal= ImageIO.read(buffer.getInputStream());
if (inputImageoriginal == null) {
return null;
} else {
BufferedImage inputImage = resizeImage(inputImageoriginal);
ByteArrayOutputStream pngContent = new ByteArrayOutputStream();
ImageIO.write(inputImage, "jpg", pngContent);
InputStream is = new ByteArrayInputStream(pngContent.toByteArray());
return IOUtils.toByteArray(is);
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
BufferedImage resizeImage(BufferedImage originalImage) throws IOException {
BufferedImage resizedImage = new BufferedImage(150, 150, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics2D = resizedImage.createGraphics();
graphics2D.drawImage(originalImage, 0, 0, 150, 150, null);
graphics2D.dispose();
return resizedImage;
}
private Component createButtonsLayout() {
// TODO Auto-generated method stub
save.setWidthFull();
delete.setWidthFull();
close.setWidthFull();
save.addThemeVariants(ButtonVariant.LUMO_PRIMARY);
save.addClickShortcut(Key.ENTER);
save.addClickListener(event -> validatandSave());
delete.addClickListener(event -> fireEvent(new DeleteEvent(this, employee)));
close.addClickListener(event -> fireEvent(new CloseEvent(this)));
return new HorizontalLayout(save, delete, close);
}
private void validatandSave() {
try {
binder.writeBean(employee);
if (getImageAsByteArray() != null) {
employee.setPicture(getImageAsByteArray());
}
fireEvent(new SaveEvent(this, employee));
} catch (ValidationException e) {
// TODO Auto-generated catch block
Notification notification = Notification.show("Please Enter All Required Fields", 3000,
Position.TOP_CENTER);
}
}
public void setEmployee(Employee employee) {
this.employee = employee;
binder.readBean(employee);
}
///Operation Save/Delete Events
public static abstract class EmployeeFormEvent extends ComponentEvent<EmployeeForm> {
private Employee employee;
protected EmployeeFormEvent(EmployeeForm source, Employee employee) {
super(source, false);
this.employee = employee;
}
public Employee getEmployee() {
return employee;
}
}
public static class SaveEvent extends EmployeeFormEvent {
SaveEvent(EmployeeForm source, Employee employee) {
super(source, employee);
}
}
public static class DeleteEvent extends EmployeeFormEvent {
DeleteEvent(EmployeeForm source, Employee employee) {
super(source, employee);
}
}
public static class CloseEvent extends EmployeeFormEvent {
CloseEvent(EmployeeForm source) {
super(source, null);
}
}
public <T extends ComponentEvent<?>> Registration addListener(Class<T> eventType,
ComponentEventListener<T> listener) {
return getEventBus().addListener(eventType, listener);
}
public void addImage(Image image2) {
// TODO Auto-generated method stub
// remove(imageContainer);
if(imageContainer!=null) {
imageContainer.removeAll();
}
imageContainer.add(image2);
//add(imageContainer);
}
}
```
查看 MemoryBuffer
的实现,您必须将其丢弃并设置一个新的,例如在你的 clearBuffer()
方法中。
buffer = new MemoryBuffer();
upload.setReceiver(buffer);