javaweb 實現檔案下載的方法及執行個體代碼_java

來源:互聯網
上載者:User

javaweb 實現檔案下載

不要再說用<a>標籤下載了,這個會把檔案開啟而不是下載

例如:

 <a href="E:\MyDesktop\37fecd65330184de67d419a8d02e7081.jpg">下載</a>

如果我這樣寫,瀏覽器就會把圖片直接開啟,除非是一個瀏覽器打不開的檔案

所以我們還是要用到java本身的檔案讀寫來進行檔案的下載

<a href="downloadFile?filename=<s:property value='document_filename'/>">下載</a>

package com.cpsec.tang.chemical.action;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.text.SimpleDateFormat;import java.util.Calendar;import java.util.List;import java.util.Random;import javax.annotation.Resource;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.struts2.ServletActionContext;import org.springframework.stereotype.Controller;import com.cpsec.tang.chemical.biz.DocumentBiz;import com.cpsec.tang.chemical.entity.Document;import com.cpsec.tang.chemical.util.Pager;import com.opensymphony.xwork2.ActionSupport;@Controller("documentAction")public class DocumentAction extends ActionSupport{private String filename;  public String downloadFile(){    System.out.println(filename);    try {      HttpServletResponse response=ServletActionContext.getResponse();      //設定檔案MIME類型       response.setContentType(ServletActionContext.getServletContext().getMimeType(filename));       //設定Content-Disposition       response.setHeader("Content-Disposition", "attachment;filename="+filename);       //擷取目標檔案的絕對路徑       String fullFileName = ServletActionContext.getServletContext().getRealPath("/files/" + filename);       //System.out.println(fullFileName);       //讀取檔案       InputStream in = new FileInputStream(fullFileName);       //讀取目標檔案,通過response將目標檔案寫到用戶端      OutputStream out = response.getOutputStream();       //寫檔案       int b;       while((b=in.read())!= -1)       {         out.write(b);       }       in.close();       out.close();     } catch (Exception e) {      e.printStackTrace();    }    return SUCCESS;  }  }

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.