public class UploadAction extends ActionSupport { private static final long serialVersionUID = 1L; private static final String CONTENT_TYPE= "text/html; charset=utf-8"; public String execute() { HttpServletResponse response = (HttpServletResponse)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE); HttpServletRequest request = (HttpServletRequest)ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST); SingleFileUpload upload = new SingleFileUpload(); try { upload.parseRequest(request); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } String temp =ServletActionContext.getServletContext().getRealPath("/") + "upload\temp\"; //��ʱĿ¼ System.out.print("�ϴ�·����"+temp); String loadpath = ServletActionContext.getServletContext().getRealPath("/") + "upload\"; //�ϴ��ļ����Ŀ¼ File file = new File(temp); if(!file.exists()) file.mkdirs(); try { upload.upload(file); response.getWriter().write(upload.getFileItem().getName()); } catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){ // �ļ���С�������ֵ e.printStackTrace(); }catch (Exception e){ e.printStackTrace(); } return null; } } 解释每一行代码
时间: 2024-04-01 11:37:48 浏览: 58
Java实训教程 Java软件开发实战 Java开发框架介绍 struts2_表单校验失败跳input视图问题共13页.pptx
public class UploadAction extends ActionSupport {
//定义一个继承自ActionSupport的类UploadAction,用于文件上传功能
private static final long serialVersionUID = 1L;
//定义一个序列化ID,用于版本控制
private static final String CONTENT_TYPE= "text/html; charset=utf-8";
//定义一个常量CONTENT_TYPE,表示上传文件的内容类型
public String execute() {
//定义一个execute方法,用于执行文件上传操作
HttpServletResponse response = (HttpServletResponse) ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
//获取HttpServletResponse响应对象
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
//获取HttpServletRequest请求对象
SingleFileUpload upload = new SingleFileUpload();
//创建SingleFileUpload类的实例
try {
upload.parseRequest(request);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
//解析HttpServletRequest请求对象,获取上传的文件信息
String temp =ServletActionContext.getServletContext().getRealPath("/") + "upload\temp\";
//获取临时目录存储路径
System.out.print("上传路径"+temp);
//输出上传路径
String loadpath = ServletActionContext.getServletContext().getRealPath("/") + "upload\";
//获取上传文件存储路径
File file = new File(temp);
//创建文件对象
if(!file.exists())
file.mkdirs();
//如果临时目录不存在,则创建该目录
try {
upload.upload(file);
response.getWriter().write(upload.getFileItem().getName());
} catch(org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException e){
//文件大小超过限制
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
//上传文件,将文件存储到指定路径下,返回文件名
return null;
//返回null值,表示上传完成,不进行页面跳转
}
}
//类UploadAction结束
阅读全文