多myProduct模块文件上传异常:提示‘未选择文件’求助
Got it, let's figure out why your first myProduct (mP) module's file upload is throwing that error after adding a new module. I've looked at your code, and here's what's going on and how to fix it:
Root Cause
The core issue is that all your file upload components are bound to the same shared bean property: #{MyBean.modFile}. When you add a new mP module, JSF re-renders the entire list. Since every file upload component uses that single backend property, the first module's selected file state gets overwritten or reset—leading to the "file not chosen" error when you try to upload from the first module later.
Step-by-Step Fixes
1. Bind File Upload to Individual mP Records
Each mP record (the rec variable in your p:dataList) should hold its own file reference instead of relying on a global bean property. Update the p:fileUpload component to bind directly to the record:
<p:fileUpload id="modFileUpload_#{rec.id}" value="#{rec.modFile}" mode="simple" skinSimple="true" label="Choose file" update="#{id}_mPList @(.buttonPanelClass)" />
(Note: Replace #{rec.id} with a unique identifier from your mP entity if id isn't the correct field—this ensures each component has a unique ID in the JSF component tree.)
2. Adjust the Upload Button to Use the Record's File
Modify your upload command button's action to work with the file stored in the individual record, not the global bean property:
<p:commandButton value="Upload" action="#{MyBean.saveModFile(rec, modCat)}" ajax="false" update="#{id}_mPList @(.buttonPanelClass)" icon="fa fa-arrow-up green"/>
3. Update Your Backend Code
- Add a file property to your mP entity class (e.g.,
MyProduct):import org.primefaces.model.UploadedFile; public class MyProduct { // ... existing properties ... private UploadedFile modFile; // Getter and Setter public UploadedFile getModFile() { return modFile; } public void setModFile(UploadedFile modFile) { this.modFile = modFile; } } - Update your
saveModFilemethod to use the file from the passed record:public void saveModFile(MyProduct rec, String modCat) { UploadedFile file = rec.getModFile(); if (file != null && file.getSize() > 0) { // Your file saving logic here (e.g., write to disk, store in DB) // ... // Optional: Reset the file property after upload to clear the input rec.setModFile(null); } else { // Add a clear error message instead of relying on the component's generic error FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Error", "The file was not chosen")); } }
Why This Works
By binding each file upload to its own mP record, you eliminate cross-module interference. Adding new modules won't overwrite or reset the file state of existing ones, and each upload operation will only process the file associated with its specific module.
内容的提问来源于stack exchange,提问作者Martin Hofman

