struts2文件上传commons_fileUpload

一、 JSP页面用原生表单,或者struts2表单提交文件


		
		
	

二、 在struts.xml配置文件增加配置


			showImg.jsp
//储存路径配置
			/upload
		

三、 写一个src/action/UploadAction类

//封装文件四大属性:与表单属性相对应;
//uploadContentType=控件名+ContentType;
//uploadFileName=控件名+FileName;
public class UploadAction {
private File upload;
private String uploadContentType;
private String uploadFileName;
private String savePath;

public String doUpload(){
//字节数组
	byte[] byteArr=new byte[1024];
	try {
//用流接收文件
		FileInputStream fis=new FileInputStream(upload);
		FileOutputStream fos=new FileOutputStream(getSavePath()+"\\"+getUploadFileName());
			int length=fis.read(byteArr);
//如果文件大小正常,图片保存到upload文件夹
			while(length!=-1){
				fos.write(byteArr);
				length=fis.read(byteArr);
			}
			fos.flush();
			fos.close();
			fis.close();
		} catch (IOException e) {
			e.printStackTrace();
			return "upload_error";
		}
	
	return "upload_success";
}

public File getUpload() {
	return upload;
}
public void setUpload(File upload) {
	this.upload = upload;
}
public String getUploadContentType() {
	return uploadContentType;
}
public void setUploadContentType(String uploadContentType) {
	this.uploadContentType = uploadContentType;
}
public String getUploadFileName() {
	return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
	this.uploadFileName = uploadFileName;
}
//savePath路径生成:服务器路径
public String getSavePath() {
	return ServletActionContext.getServletContext().getRealPath(savePath);
			}
public void setSavePath(String savePath) {
	this.savePath = savePath;
}

}

四、 在下一个JSP页面显示出来


在这里插入图片描述

你可能感兴趣的:(Struts2)