private File file; private String fileFileName; private String picture; //都有getter 和 setter InputStream is = new FileInputStream(file); //引入一個IO流的輸入資料流String root = ServletActionContext.getRequest() .getRealPath("/bookpicture"); //通過REQUEST來得到相對位址,並在後面加上/bookpictureFile f = new File(root, this.getFileFileName()); //定義一個FILE檔案,第一個參數是檔案的路徑,第二個是檔案的名字picture="."+"\\"+"bookpicture"+"\\"+this.getFileFileName();//為PICTURE字串賦值,/地址/檔案名稱 System.out.println ("======picture====="+picture); //從控制台輸出PictureOutputStream os = new FileOutputStream(f); //第一個檔案的輸出資料流byte[] buffer = new byte[1024];//定義一個bufer的字串,長度為1024 int len = 0; while ((len = is.read(buffer)) > 0) { //如果從制定檔案中讀取到的資訊為結束就繼續迴圈os.write(buffer, 0, len); //將檔案讀出的內容寫入到指定的檔案中}
package com;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;import com.jspsmart.upload.*;public class uploadfiles extends HttpServlet{public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{//使用了一個第三方的組件,存放在web-inf/lib下 response.setContentType("text/html;charset=GB2312"); //由於SmartUpload的初始化方法需要pageContext,所以我們在servlet中得到他 //為了得到pageConext要首先得到JspFactory的執行個體 //通過JspFactory的執行個體的getPageContext方法得到pageConext的執行個體JspFactory jf = null;//得到JspFactory的執行個體jf=JspFactory.getDefaultFactory();/*getPageContext(Servlet servlet, ServletRequest request, ServletResponse response, java.lang.String errorPageURL, boolean needsSession, int buffer, boolean autoflush) */ PageContext pageContext=jf.getPageContext(this,request,response,null,true,8192,true);try{//執行個體化SmartUploadSmartUpload mySmartUpload=new SmartUpload();//初始化SmartUpload的執行個體,需要PageContext的執行個體mySmartUpload.initialize(pageContext);//設定最大上傳的位元組數,其實可以不進行設定,表示上傳的檔案沒有大小限制//mySmartUpload.setTotalMaxFileSize(10000000);mySmartUpload.upload();//下面是單檔案上傳//上傳的檔案以com.jspsmart.upload.File 代表,如果檔案名稱重複,則進行覆蓋com.jspsmart.upload.File file=mySmartUpload.getFiles().getFile(0);String upLoadFileName=file.getFileName();//調用com.jspsmart.upload.File執行個體的saveas的方法儲存檔案,此時的檔案名稱即是//儲存到伺服器上的檔案名稱file.saveAs("/upload/"+upLoadFileName);Request req = Text t = .....;t.setUpload(upLoadFileName);t.set.....(req);}catch(SmartUploadException e){System.out.println(e.getMessage());}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException{doGet(request,response);}}