1. 程式人生 > >Struts2+jsp上傳和下載檔案

Struts2+jsp上傳和下載檔案

public class FileUploadAction extends ActionSupport{
//上傳的檔案
private File uploadFile;
//上傳檔案的型別
private String uploadFileContentType;
//上傳檔案的名字
private String uploadFileFileName;
//上傳檔案的儲存路徑(相對)
private String savePath;
@Override
public String execute() throws Exception {
try {
//通過上傳的檔案獲取輸入流
InputStream is = new FileInputStream(uploadFile);
//獲取上傳檔案儲存的絕對路徑
String uploadPath = ServletActionContext.getServletContext().getRealPath(savePath);
//接下來的3行用來判斷是否存在儲存檔案的目錄,如果不存在則建立
File file = new File(uploadPath);
if(!file.exists()){
file.mkdirs();
}
//獲取儲存檔案的File
File toFile = new File(uploadPath,this.getUploadFileFileName());
//根據改file獲取輸出流,用於儲存檔案
OutputStream os = new FileOutputStream(toFile);
//快取
byte[] buffer = new byte[1024];
int length = 0;
//讀取輸入流的資料,儲存在buffer中,並用length獲取輸入流讀取的位元組數,如果lengh不大於0則代表已無資料可讀
while((length=is.read(buffer))>0){
//通過儲存在buffer中的資料和讀取的位元組數,向輸出流寫資料(即儲存)
os.write(buffer,0,length);
}
os.flush();
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
throw new Exception(e);
}
return SUCCESS;
}