上传的Action,UploadExcel为ActionForm,里面有一个FormFile的属性,主要是得到它的InputStream,然后写入磁盘
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
UploadExcel uaf = (UploadExcel) form;
FormFile myFile = uaf.getMyfile();
if(myFile == null){
request.setAttribute("error", "请选择你要导入的试题");
return mapping.findForward("fail");
}else if (myFile != null) {
System.out.println("fileName=" + myFile.getFileName());
FileOutputStream fos;
try {
fos = new FileOutputStream("c://"+ myFile.getFileName());
InputStream stream = myFile.getInputStream();
fos.write(myFile.getFileData());
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return mapping.findForward("fail");
下载的Action
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
try {
File file=new File("E://你好bb.xls");
String fileName=file.getName();
InputStream is=new FileInputStream(file);
OutputStream os= response.getOutputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BufferedOutputStream bos = new BufferedOutputStream(os);
fileName = java.net.URLEncoder.encode(fileName, "UTF-8");// 处理中文文件名的问题
fileName = new String(fileName.getBytes("UTF-8"), "GBK");//处理中文文件名的问题
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("application/msexcel");// 不同类型的文件对应不同的MIME类型
response.setHeader("Content-Disposition","attachment; filename="+fileName);
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = bis.read(buffer)) != -1){
bos.write(buffer, 0, bytesRead);// 将文件发送到客户端
}
bos.flush();
bis.close();
bos.close();
is.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapping.findForward("");
}
本文介绍如何使用Struts2框架实现文件的上传与下载功能。具体包括使用FormFile获取上传文件的输入流并将其保存到指定路径,以及设置响应头等步骤实现文件下载。
319

被折叠的 条评论
为什么被折叠?



