Name multiple file field objects with the same name in the upload.jsp page, so that multiple file fields can be parsed into an array in the action. The size of the array is the number of file fields. At the same time, one file field is parsed into Three corresponding variables, so multiple file fields correspond to three arrays, where the size of each array is the number of file fields. The jsp page code is as follows:
</form>
The corresponding Action traverses all file fields in sequence, and then generates the corresponding input file stream. The output file stream adds the corresponding output file stream to save the file in the specified server storage path. At the same time, dynamically specify the saving path of the file on the server.
The action code is as follows:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadAction extends ActionSupport {
private String title;
private File[] upload;
private String[] uploadFileName;
private String[] uploadContentType;
private String savePath;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public File[] getUpload() {
return upload;
}
public void setUpload(File[] upload) {
this.upload = upload;
}
public String[] getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String[] uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String[] getUploadContentType() {
return uploadContentType;
}
public void setUploadContentType(String[] uploadContentType) {
this.uploadContentType = uploadContentType;
}
public String getSavePath() {
return ServletActionContext.getRequest().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String upload()throws Exception{
File[] files=this.getUpload();
for(int i=0;i<files.length;i++){
FileOutputStream fos=new FileOutputStream(this.getSavePath()+"//"+this.getUploadFileName()[i]);
byte[] buffer=new byte[1024];
FileInputStream fis=new FileInputStream(files[i]);
int len=0;
while((len=fis.read(buffer))>0){
fos.write(buffer,0,len);
}
}
return SUCCESS;
}
}
The struts.xml file is configured as follows: configure the interceptor for file upload, allowed upload file types, upload file size limit, and introduce the defaultStack interceptor and the storage location of the uploaded file on the server.
</struts>
The success.jsp page code is as follows: