struts1儲存上傳圖片及檔案--Java類代碼__我的經驗總結
來源:互聯網
上載者:User
public ActionForward updateLoad(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {
PrintWriter out = response.getWriter();
String base64 = request.getParameter("base64");
System.out.println(base64);
String localhost=request.getServerName();//localhost
String CreditPlatform=request.getContextPath();//CreditPlatform
int duank=request.getServerPort();//8080
String dirPath = getServlet().getServletContext().getRealPath("/colorlife/upload");
Hashtable files = form.getMultipartRequestHandler().getFileElements();
List<String> list = new ArrayList<String>();
for(Enumeration e = files.keys(); e.hasMoreElements();) {
String key = (String) e.nextElement();
FormFile formfile = (FormFile) files.get(key);
String filename = formfile.getFileName().trim();
if (!"".equals(filename)) {
InputStream ins = formfile.getInputStream();
//擷取item中的上傳檔案的輸入資料流
InputStream in = formfile.getInputStream();
//建立一個檔案輸出資料流
dirPath=PathUtil.isExist(dirPath,"cllife","car").replace("/", "\\")+filename;
//返回圖片路徑
//
String purl = dirPath.substring(dirPath.lastIndexOf("colorlife")-1);
String url="http://"+localhost+":"+duank+CreditPlatform+purl;
url = url.replace("\\", "/");
list.add(url);
FileOutputStream out1 = new FileOutputStream(dirPath);
//建立一個緩衝區
byte buffer[] = new byte[1024];
//判斷輸入資料流中的資料是否已經讀完的標識
int len = 0;
//迴圈將輸入資料流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料
while((len=in.read(buffer))>0){
//使用FileOutputStream輸出資料流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中
out1.write(buffer, 0, len);
}
//關閉輸入資料流
in.close();
//關閉輸出資料流
out1.close();
}
}