javaWeb中在servlet中response下載圖片
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 測試在servlet中,傳送請求 下載圖片
*
* @author k.sea
*
*/
public class DownLoadImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// 獲取當前目錄的圖片路徑
// String path=this.getServletContext().getRealPath("/image/tuxing.png");
String path=this.getServletContext().getRealPath("/image/水星.png");
// 獲取檔名
String fileName=path.substring(path.lastIndexOf("\\")+1);
System.out.println(fileName);
//制定瀏覽器頭
//在下載的時候這裡是英文是沒有問題的
//resp.setHeader("content-disposition", "attachment;fileName="+fileName);
//如果圖片名稱是中文需要設定轉碼
resp.setHeader("content-disposition", "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
InputStream reader = null;
OutputStream out = null;
byte[] bytes = new byte[1024];
int len = 0;
try {
// 讀取檔案
reader = new FileInputStream(path);
// 寫入瀏覽器的輸出流
out = resp.getOutputStream();
while ((len = reader.read(bytes)) > 0) {
out.write(bytes, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader != null) {
reader.close();
}
if (out != null)
out.close();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
}