Struts2 上传下载
页面
<form action="" method="" name="" enctype="multipart/form-data" >
<input type="file" name="file"/>
</form>
?
配置文件
<action name="addFile" method="对应方法">
??? ??<param name="savePath">/imageUpload/file</param>
??? ??<result name="success" type="redirect-action">
??? ???fileList.action
??? ??</result>
</action>
?
action
属性? 起个名字叫file?? struts2中您需要些3个属性?? file?? fileContentType?? fileFileName
?private File file;//文件
?private String fileContentType;//
?private String fileFileName;
?private String savePath;//保存路径
//**********setter?? and??? getter**********//
public String addFile(){
??String paths=ServletActionContext.getServletContext().getRealPath(savePath);
? File saveDirectory=new File(paths);
??if(!saveDirectory.exists()){//检查文件夹是否存在? 不存在则创建
???saveDirectory.mkdirs();
??}
? String names=fileFileName.substring(fileFileName.indexOf("."));//截取字符串
??DateFormat df=new SimpleDateFormat("yyMMddHHmmss");//格式化日期
? String saveName=df.format(new Date())+names;
? saveFile(new File(paths+"/"+saveName));
}
?
//上传文件
public void saveFile(File outputFile){
??try {
???FileOutputStream fos=new FileOutputStream(outputFile);
???BufferedOutputStream bos=new BufferedOutputStream(fos);
???
???FileInputStream fis=new FileInputStream(this.file);
???BufferedInputStream bis=new BufferedInputStream(fis);
???
???byte[] buffer=new? byte[1024];
???int length=-1;
???while((length=fis.read(buffer))!=-1){
????bos.write(buffer,0,length);
???}
???bos.close();
???fos.close();
???bis.close();
???fis.close();
??} catch (FileNotFoundException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??} catch(IOException e){
???e.printStackTrace();
??}
?}
?
//下载方法???? 三个参数?? response丢想?? 路径filePath? 文件名filename
public void httpStream(HttpServletResponse response,String filePath,String filename)throws Exception
?{
??FileInputStream fileInputStream=new FileInputStream(filePath);
??BufferedInputStream br=new BufferedInputStream(fileInputStream);
??byte[] buf=new byte[1024];
??int len=0;
??response.reset();
??response.setContentType("application/x-msdownload");
??response.setHeader("Content-Disposition","attachment:filename="+URLEncoder.encode(filename,"utf-8"));
??OutputStream out=response.getOutputStream();
??while((len=br.read(buf))>0)
???out.write(buf,0,len);
??br.close();
??out.close();
??fileInputStream.close();
?}
?
从网上摘的代码,记录下来,万一以后忘了就不好了