struts 实现文件上传与下载

本文介绍如何使用Struts2框架实现文件的上传与下载功能。具体包括使用FormFile获取上传文件的输入流并将其保存到指定路径,以及设置响应头等步骤实现文件下载。

上传的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("");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值