struts 實現文件上傳與下載

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

發佈了32 篇原創文章 · 獲贊 4 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章