文件上传
- 导入相关jar包
commons-io-2.2.jar
与commons-fileupload-1.3.2.jar
- 编写action类在类中添加File类型的参数,供自动化接收数据
public class FileAction extends ActionSupport{
//接收文件数据,应当与前端上传文件域的名称相同
private File uploadfile;
//接收上传的文件名,命名格式为File类型属性名+FileName,如此例为"uploadfile+FileName";
private String uploadfileFileName;
//接收上传的文件类型,命名格式为File类型属性名+ContentType,如此例为"uploadfile+ContentType";
private String uploadfileContentType;
//接收Struts.xml文件中的文件存放路径,也可直接在java中写死
private String savePath;
public String upload(){
System.out.println(savePath);
//自定义封装的文件上传工具类
String state = Fileutils.uploadFile(uploadfile, uploadfileFileName, savePath);
return state;
}
//get(),set()方法省略
为了方便调用,自己编写了一个写文件的类;源代码如下:
public class Fileutils {
public static String uploadFile(File file,String FileName,String savePath){
FileInputStream fis =null;
FileOutputStream fos = null;
try {
fis = new FileInputStream(file);
fos = new FileOutputStream(new File(savePath,FileName));
byte[] b = new byte[1024];
int length = fis.read(b);
while(length!=-1){
fos.write(b, 0, length);
length = fis.read(b);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error";
}finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "error";
}
}
return "success";
}
}
- 编写struts.xml配置文件
<action name="*File" class="action.FileAction" method="{1}">
<!-- 此为上传文件的保存路径 -->
<param name="savePath">/upload</param>
<!-- 文件上传成功的跳转页面 -->
<result name="success">/fileSuccess.jsp</result>
<result name="error">/upload.jsp</result>
</action>
- 编写前端页面,前端页面中
input
的类型为file
,name值与action类中的属性名一致,form
标签的method
提交方式必须为post
,enctype
为multipart/form-data
<form action="uploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="uploadfile">
<input type="submit" value="上传">
</form>
文件下载
- 创建Action类,类中获取要下载目标文件的 输入流 ,
并且提供 getInputStream()方法,供struts2自动调用获取输入流使用
public class DownFileAction {
private String fileName;
private InputStream inputStream;
public String down(){
inputStream = ServletActionContext.getServletContext().getResourceAsStream("/upload/"+fileName);
try {
//更改编码格式,防止出现下载中文乱码,无文件名无法下载问题
fileName=new String(fileName.getBytes("UTF-8"),"ISO8859-1");
System.out.println(fileName);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
}
- 配置struts.xml标签
<action name="downFile" class="action.DownFileAction" method="down">
<result name="success" type="stream">
<param name="contentType"> image/jpeg </param>
<param name="inputName"> inputStream </param>
<!--${fileName}为动态获取参数名作为下载附件的 默认文件名 -->
<param name="contentDisposition"> attachment ; filename = ${fileName} </param>
<param name="bufferSize">1024</param>
</result>
</action>