1. 程式人生 > >JSP web 實現檔案上傳下載程式碼

JSP web 實現檔案上傳下載程式碼

jsp程式碼 實現檔案上傳下載

package util;

import java.io.FileInputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class UploadDown {
/**
* @discription 下載檔案
* @param aFilePath 要下載的檔案路徑
* @param aFileName 要下載的檔名
* @param response 響應物件
*/
public static void downLoad(String aFilePath, String aFileName, HttpServletResponse response){
FileInputStream in = null; //輸入流
ServletOutputStream out = null; //輸出流
try {
//設定下載檔案使用的報頭
response.setHeader(“Content-disposition”, “attachment; filename=”
+ aFileName);
// 讀入檔案
in = new FileInputStream(aFilePath + aFileName);
//得到響應物件的輸出流,用於向客戶端輸出二進位制資料
out = response.getOutputStream();
out.flush();
int aRead = 0;
byte b[] = new byte[1024];
while ((aRead = in.read(b)) != -1 & in != null) {
out.write(b,0,aRead);
}
out.flush();
in.close();
out.close();
} catch (Throwable e) {
e.printStackTrace();
}
}

}