struts實現資源的上傳下載

下面爲下載所有類型的資源的代碼!

public ActionForward downloadData(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  ActionForward forward = null;
  String newsId = request.getParameter(Constants.NEWS_ID).trim();
  request.setCharacterEncoding("gb2312");
  response.setContentType("text/html;charset=gb2312");
  ActionErrors errors = new ActionErrors();
  try {
   NewsCnt cnt = this.showService.searchNews(newsId);
   String filePath = cnt.getCntUrl();
   // filePath = URLEncoder.encode(filePath, "UTF-8");
   log.debug("----->>>>filePaht = " + filePath);
   // // 設置爲下載
   String fileName = filePath.substring(
     filePath.lastIndexOf("//") + 1, filePath.lastIndexOf("."));
   String postfix = filePath.substring(filePath.lastIndexOf(".") + 1,
     filePath.length());
   log.debug("----->>>>fileName = " + fileName);
   response.setContentType("application/x-download");
   response.addHeader("Content-Disposition", "attachment;filename="
     +   "download." + postfix);
   OutputStream out = response.getOutputStream();
   FileInputStream in = new FileInputStream(filePath);
   byte[] buffer = new byte[1024];
   int len = 0;
   while ((len = in.read(buffer)) > 0) {
    out.write(buffer, 0, len);
   }
   out.flush();
   log.debug("資料下載成功!");
   forward = mapping.findForward("downloadDataPath");
  } catch (Exception e) {
   log.debug("資料下載時出現異常:" + e.getMessage());
   errors.add(Constants.ERROR_KEY, new ActionError(
     "download.data.exception", MessageResources
       .getMessageResources(Constants.RESOURCE_KEY)));
   forward = mapping.getInputForward();
  }
  return forward;
 }

這裏簡單說下需要注意的幾點問題!

1.定義輸出類型,和設置輸出文件頭 

   response.setContentType("application/x-download");
   response.addHeader("Content-Disposition", "attachment;filename="
     +   "download." + postfix);

 (1) 當下載excel文件時設置如下:

   // 設定輸出文件頭
   response.setHeader("Content-disposition",
     "attachment;filename=module.xls");
   // 定義輸出類型
   response.setContentType("application/msexcel");

 (2)當下載word文件時設置如下:

   // 設定輸出文件頭
   response.setHeader("Content-disposition",
     "attachment;filename=module.doc");
   // 定義輸出類型
   response.setContentType("application/msword");

2.文件名不能爲中文(這個到現在還沒弄清楚)
     response.addHeader("Content-Disposition", "attachment;filename="
     +   "download." + postfix);

    即"download"不能爲中文,開始試過用源文件名來做下載的文件名,但是當文件名包含中文就不能下載

   因此,將文件名改成了"download"。上面postfix爲擴展名

 3.到現在,文件頭的設置和輸出類型的定義,還沒完全弄清楚

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章