TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
Struts对Apache的commons-fileupload进行了再封装,把上传的文件封装成FormFile对象,直接获取该对象,将文件保存即可。
1,UploadForm.java:
private String action;
private String text;
private FormFile file;
2,upload.jsp:
<HTML:form action="/upload?action=upload" method="post" enctype="multipart/form-data">
文件 : <html:file property="file" style="width:200px;"/><html:errors property="file"/><br/>
备注 : <html:textarea property="text" style="width:200px;"/><html:errors property="text"/><br/>
<html:submit value="开始上传"/>
</html:form>
3,UploadAction.java:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UploadForm uploadForm = (UploadForm) form;// TODO Auto-generated method stub
if("upload".equals(uploadForm.getAction())){
return upload(mapping,form,request,response);
}
return mapping.getInputForward();
}
public ActionForward upload(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
UploadForm uploadForm = (UploadForm) form;// TODO Auto-generated method stub
StringBuffer buffer = new StringBuffer();
buffer.append("<style>body{font-size:12px;}</style>");
if(uploadForm.getFile() != null&& uploadForm.getFile().getFileSize() > 0){
//获取文件夹/WEB-INF/classes
File classes = new File(getClass().getClassLoader().getResource("").getFile());
//获取文件夹/upload
File uploadFolder = new File(classes.getParentFile().getParentFile(),"upload");
uploadFolder.mkdirs(); //创建父文件夹
//保存到/upload下面
File file = new File(uploadFolder,uploadForm.getFile().getFileName());
OutputStream ous = null; //文件输出流
InputStream ins = null; //上传文件输入流
try{
byte[] b = new byte[1024]; //缓存数组
int len = 0;
ins = uploadForm.getFile().getInputStream(); //上传文件输入流
ous = new FileOutputStream(file); //文件输出流
while((len = ins.read(b)) != -1)
ous.write(b,0,len); //循环写到文件中
}finally{
ins.close();
ous.close();
}
buffer.append("文件:<a href=upload/"+file.getName()+" target=_blank>"+file.getName()+"</a><br/>");
}else{
buffer.append("文件:没有选择文件<br/>");
}
buffer.append("备注:"+uploadForm.getText()+"<br/>");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(buffer.toString());//直接输出内容到客户端
return null;
} |
|