jsp上傳
❶ jsp簡單上傳代碼
servlet文件上傳
login.jsp
<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
輸入用戶名<input typ="text" name ="username">
<input type="file"name="file"/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
result.jsp
<%@ page language="java" contentType="text/html; charset=gbk"
    pageEncoding="gbk"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>上傳結果頁面</title>
</head>
<body>
username:${requestScope.username }
filename:${requestScope.file }
</body>
</html>
UploadServlet.java
package com.test.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
    public UploadServlet() {
    }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
   String path = request.getSession().getServletContext().getRealPath("/upload");
   DiskFileItemFactory factory = new DiskFileItemFactory();
  
   factory.setRepository(new File(path));
   factory.setSizeThreshold(1024 * 1024);
  
   ServletFileUpload upload = new ServletFileUpload(factory);
  
   try
   {
    List<FileItem>list = upload.parseRequest(request);
    for(FileItem item:list){
     if(item.isFormField()){
      String name = item.getFieldName();
      String value = item.getString("utf-8");
      request.setAttribute(name, value);
     }
     else{
      String name = item.getFieldName();
      String value = item.getName();
      int start = value.lastIndexOf("\\");
      String fileName = value.substring(start+1);
      request.setAttribute(name, fileName);
      System.out.println(fileName);
      OutputStream os = new FileOutputStream(new File(path,fileName));
      InputStream is = item.getInputStream();
     
      byte[] buffer = new byte[400];
      int length = 0;
      while((length = is.read(buffer))>0){
       os.write(buffer,0,length);
      }
      os.close();
      is.close();
     }
    }
   }
   catch(Exception e){
    e.printStackTrace();
   }
  
   request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
Struts文件上傳
1.創建一個工程:
創建一個JSP頁面內容如下:
  <body>
   <form action="uploadAction.do" method="post" enctype="multipart/form-data" >
   <input type="file" name="file">
   <input type="submit">
   </form>
  </body>
2.創建一個FormBean繼承ActionForm
其中有個private FormFile file ;屬性。FormFile類的全名為:org.apache.struts.upload.FormFile 
3.創建一個UploadAction繼承自Action
然後重寫Action的execute()方法:
代碼如下:
public ActionForward execute(ActionMapping mapping, ActionForm form,
                            HttpServletRequest request, HttpServletResponse response) {
                   UploadForm uploadForm = (UploadForm) form;
                   if(uploadForm.getFile()!=null)
                            FileUtil.uploadFile(uploadForm.getFile(), "e:/abc/accp");
                   return null;
}
4.創建FileUtil工具類,裡面實現上傳的文件的方法:
關鍵代碼如下:
public class FileUtil 
{        
/*** 創建空白文件
          * @param fileName 文件名
          * @param dir 保存文件的目錄
          * @return
          */
         private static File createNewFile(String fileName,String dir)
         {                 
                   File dirs = new File(dir);
                   //看文件夾是否存在,如果不存在新建目錄
                   if(!dirs.exists())
                            dirs.mkdirs();             
                   //拼湊文件完成路徑
                   File file = new File(dir+File.separator+fileName);               
                            try {  
                                     //判斷是否有同名名字,如果有同名文件加隨機數改變文件名
                                     while(file.exists()){
                                               int ran = getRandomNumber();
                                               String prefix = getFileNamePrefix( fileName);
                                               String suffix = getFileNameSuffix( fileName);
                                               String name = prefix+ran+"."+suffix;
                                               file = new File(dir+File.separator+name);
                                     }                                    
                                     file.createNewFile();
} catch (IOException e) {
                                     // TODO Auto-generated catch block
                                     e.printStackTrace();
                            }
                            return file;
         }
         /**
          * 獲得隨機數
          * @return
          */
         private  static int getRandomNumber()      {
                   Random random = new Random(new Date().getTime());               
                   return Math.abs(random.nextInt());
         }
         /**
          * 分割文件名 如a.txt 返回 a
          * @param fileName 
          * @return
          */
         private static String getFileNamePrefix(String fileName){
                   int dot = fileName.lastIndexOf(".");
                   return fileName.substring(0,dot);
         }
         /**
          * 獲得文件後綴
          * @param fileName
          * @return
          */
         private static String getFileNameSuffix(String fileName)   {
                   int dot = fileName.lastIndexOf(".");           
                   return fileName.substring(dot+1);
         }        
/**
          * 上傳文件
          * @param file
          * @param dir
          * @return
 */
         public static String uploadFile(FormFile file,String dir)
         {
                   //獲得文件名
                   String fileName = file.getFileName();
                   InputStream in = null;
                   OutputStream out  = null;
                   try 
                   {
                            in = new BufferedInputStream(file.getInputStream());//構造輸入流
                            File f = createNewFile(fileName,dir);
                             out = new BufferedOutputStream(new FileOutputStream(f));//構造文件輸出流
                            byte[] buffered = new byte[8192];//讀入緩存
                            int size  =0;//一次讀到的真實大小
                            while((size=in.read(buffered,0,8192))!=-1)
                            {
                                     out.write(buffered,0,size);
                            }
                            out.flush();
} catch (FileNotFoundException e) {   
                            e.printStackTrace();
                   } catch (IOException e) {
                            e.printStackTrace();
                   }
                   finally
                   {
                            try {
                                     if(in != null) in.close();
                            } catch (IOException e) {
                                     e.printStackTrace();
                            }
                            try {
                                     if(out != null) out.close();
                            } catch (IOException e) {
                                     // TODO Auto-generated catch block
                                     e.printStackTrace();
                            }
                   }
                   return null;
         }
}
❷ 怎麼在 jsp 頁面中上傳文件
使用jsp smartupload
示例:部分文件代碼  具體實現 找些教材
 
UploadServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.*;
import java.text.*;
import java.util.*;
/*******************************************************/
/*    該實例中盡可能多地用到了一些方法,在實際應用中            */
/*     我們可以根據自己的需要進行取捨!                         */
/*******************************************************/
public class UploadServlet extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 新建一個SmartUpload對象,此項是必須的
		SmartUpload myupload = new SmartUpload();		
		// 初始化,此項是必須的
		ServletConfig config = getServletConfig();
		myupload.initialize(config,request,response);		
		response.setContentType("text/html");
		response.setCharacterEncoding("gb2312");
		PrintWriter out = response.getWriter();
		out.println("<h2>處理上傳的文件</h2>");
		out.println("<hr>");
		
		try{			
			// 限制每個上傳文件的最大長度
			myupload.setMaxFileSize(1024*1024);		
			// 限制總上傳數據的長度
			myupload.setTotalMaxFileSize(5*1024*1024);		
			// 設定允許上傳的文件(通過擴展名限制)
			 myupload.setAllowedFilesList("doc,txt,jpg,gif");	
			// 設定禁止上傳的文件(通過擴展名限制)
			 myupload.setDeniedFilesList("exe,bat,jsp,htm,html,,");			
			// 上傳文件,此項是必須的
			myupload.upload();			
			// 統計上傳文件的總數
			int count = myupload.getFiles().getCount();			
			// 取得Request對象
			Request myRequest = myupload.getRequest();		
			String rndFilename,fileExtName,fileName,filePathName,memo;
			Date dt = null; 
			SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); 			
			
			// 逐一提取上傳文件信息,同時可保存文件	
			for (int i=0;i<count;i++)
			{
				//取得一個上傳文件
				File file = myupload.getFiles().getFile(i);				
				// 若文件不存在則繼續
				if (file.isMissing()) continue;		
				// 取得文件名
				fileName = file.getFileName();
				// 取得文件全名
				filePathName = file.getFilePathName();
				// 取得文件擴展名
				fileExtName = file.getFileExt();
				// 取得隨機文件名
				dt = new Date(System.currentTimeMillis()); 
				Thread.sleep(100);
				rndFilename= fmt.format(dt)+"."+fileExtName;			
				memo = myRequest.getParameter("memo"+i);
	
				// 顯示當前文件信息
				out.println("第"+(i+1)+"個文件的文件信息:<br>");
				out.println(" 文件名為:"+fileName+"<br>");
				out.println(" 文件擴展名為:"+fileExtName+"<br>");
				out.println(" 文件全名為:"+filePathName+"<br>");
				out.println(" 文件大小為:"+file.getSize()+"位元組<br>");
				out.println(" 文件備注為:"+memo+"<br>");
				out.println(" 文件隨機文件名為:"+rndFilename+"<br><br>");
		
				// 將文件另存,以WEB應用的根目錄作為上傳文件的根目錄
				file.saveAs("/upload/" + rndFilename,myupload.SAVE_VIRTUAL);
			}
			out.println(count+"個文件上傳成功!<br>");			
		}catch(Exception ex){
			out.println("上傳文件超過了限制條件,上傳失敗!<br>");
			out.println("錯誤原因:<br>"+ex.toString());
		}
		out.flush();
		out.close();
	}
}
❸ jsp文件上傳
public class MultipartTestServlet extends HttpServlet { 
public MultipartTestServlet() { //構造方法
super(); 
} 
public void doPost(HttpServletRequest request, HttpServletResponse response) //servlet的doPost方法處理POST請求 
throws ServletException, IOException { //拋出異常
request.setCharacterEncoding("gbk"); //設置字元為GBK
RequestContext requestContext = new ServletRequestContext(request); //實例化RequestContext對象
if(FileUpload.isMultipartContent(requestContext)){ 
//判斷是否包含 multipart 內容
DiskFileItemFactory factory = new DiskFileItemFactory(); 
 //  創建基於磁碟的文件工廠
factory.setRepository(new File("c:/tmp/")); // 設置臨時目錄
ServletFileUpload upload = new ServletFileUpload(factory); 
upload.setHeaderEncoding("gbk"); 
upload.setSizeMax(2000000); //設置緩沖區大小
List items = new ArrayList(); 
try { 
items = upload.parseRequest(request); // 得到所有的文件
} catch (FileUploadException e1) { 
System.out.println("文件上傳發生錯誤" + e1.getMessage()); 
} 
Iterator it = items.iterator(); 
while(it.hasNext()){ 
FileItem fileItem = (FileItem) it.next(); 
if(fileItem.isFormField()){ 
System.out.println(fileItem.getFieldName() + " " + fileItem.getName() + " " + new String(fileItem.getString().getBytes("iso8859-1"), "gbk")); //獲得表單中域的名字。獲得從瀏覽器中取得的文件全路徑
}else{ 
System.out.println(fileItem.getFieldName() + " " + 
fileItem.getName() + " " + 
fileItem.isInMemory() + " " + 
fileItem.getContentType() + " " + 
fileItem.getSize()); 
if(fileItem.getName()!=null && fileItem.getSize()!=0){
// 瀏覽器中取得的文件全路徑不為空 大小 不為0 則寫入
File fullFile = new File(fileItem.getName()); 
File newFile = new File("c:/temp/" + fullFile.getName()); 
try { 
fileItem.write(newFile); 
} catch (Exception e) { 
e.printStackTrace(); 
} 
}else{ 
System.out.println("文件沒有選擇 或 文件內容為空"); 
} 
} 
} 
} 
} 
}
❹ jsp如何上傳文件
只是jsp部分的話,只要在form標簽里加一個「enctype="multipart/form-data"」就好了,讀取下載的話只要弄個commons-fileupload之類的插件就很容易解決
這里是下載部分的核心代碼:
<%@ page contentType="text/html;charset=gb2312" import="com.jspsmart.upload.*" %>
<%
 String sUrl = (String)request.getAttribute("fileurl");
 SmartUpload su = new SmartUpload();
 su.initialize(pageContext);
 //設定contentDisposition為null以禁止瀏覽器自動打開文件,保證點擊鏈接後是下載文件。若不設定,則下載的文件擴展名為doc時,瀏覽器將自動用word打開它;擴展名為pdf時,瀏覽器將用acrobat打開。
 su.setContentDisposition(null);
 su.downloadFile(sUrl);
%>
但是歸根結底,你還是要一個存放文件路徑的資料庫啊,否則你下載時候下載地址每次都寫死或者手動輸入??如果要動態讀取的話還是要建一個存放文件路徑的資料庫的
❺ jsp怎麼上傳文件
上傳文件程序應用示例
<form action="doUpload.jsp" method="post" enctype="multipart/form-data">
<%-- 類型enctype用multipart/form-data,這樣可以把文件中的數據作為流式數據上傳,不管是什麼文件類型,均可上傳。--%>
請選擇要上傳的文件<input type="file" name="upfile" size="50">
<input type="submit" value="提交">
</form>
</body>
</html>
doUpload.jsp
<%@ page contentType="text/html; charset=GBK" %>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<html><head><title>upFile</title></head>
<body bgcolor="#ffffff">
<%
//定義上載文件的最大位元組
int MAX_SIZE = 102400 * 102400;
// 創建根路徑的保存變數
String rootPath;
//聲明文件讀入類
DataInputStream in = null;
FileOutputStream fileOut = null;
//取得客戶端的網路地址
String remoteAddr = request.getRemoteAddr();
//獲得伺服器的名字
String serverName = request.getServerName();
//取得互聯網程序的絕對地址
String realPath = request.getRealPath(serverName);
realPath = realPath.substring(0,realPath.lastIndexOf("\\"));
//創建文件的保存目錄
rootPath = realPath + "\\upload\\";
//取得客戶端上傳的數據類型
String contentType = request.getContentType();
try{
if(contentType.indexOf("multipart/form-data") >= 0){
//讀入上傳的數據
in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
if(formDataLength > MAX_SIZE){
out.println("<P>上傳的文件位元組數不可以超過" + MAX_SIZE + "</p>");
return;
}
//保存上傳文件的數據
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
//上傳的數據保存在byte數組
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes,totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
//根據byte數組創建字元串
String file = new String(dataBytes);
//out.println(file);
//取得上傳的數據的文件名
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0,saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
//取得數據的分隔字元串
String boundary = contentType.substring(lastIndex + 1,contentType.length());
//創建保存路徑的文件名
String fileName = rootPath + saveFile;
//out.print(fileName);
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
pos = file.indexOf("\n",pos) + 1;
int boundaryLocation = file.indexOf(boundary,pos) - 4;
//out.println(boundaryLocation);
//取得文件數據的開始的位置
int startPos = ((file.substring(0,pos)).getBytes()).length;
//out.println(startPos);
//取得文件數據的結束的位置
int endPos = ((file.substring(0,boundaryLocation)).getBytes()).length;
//out.println(endPos);
//檢查上載文件是否存在
File checkFile = new File(fileName);
if(checkFile.exists()){
out.println("<p>" + saveFile + "文件已經存在.</p>");
}
//檢查上載文件的目錄是否存在
File fileDir = new File(rootPath);
if(!fileDir.exists()){
fileDir.mkdirs();
}
//創建文件的寫出類
fileOut = new FileOutputStream(fileName);
//保存文件的數據
fileOut.write(dataBytes,startPos,(endPos - startPos));
fileOut.close();
out.println(saveFile + "文件成功上載.</p>");
}else{
String content = request.getContentType();
out.println("<p>上傳的數據類型不是multipart/form-data</p>");
}
}catch(Exception ex){
throw new ServletException(ex.getMessage());
}
%>
</body>
</html>
❻ jsp頁面中如何視頻文件上傳的代碼實現
jsp 獲取視頻文件進行播放 跟html沒什麼區別 可以調用不同播放器的代碼 ,比如MEDIA播放器:
  <OBJECT   ID="mediaplayer"   WIDTH="50%"   HEIGHT="50%"   CLASSID="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">   
  <!--播放的文件的地址-->   
  <param   name="url"   value="http://www..com"/>   
      <!--去除右鍵菜單-->   
  <param   name="enableContextMenu"   value="false"/>   
  <param   name="autoStart"   value="true"   />   
  </OBJECT>
❼ JSP如何上傳圖片
jsp使用I/O文件操作類,可以將圖片轉成二進制的形式,然後保存在伺服器中的一個文件夾,示例如下:
<%...@pagecontentType="text/html;charset=gb2312"%>
<%...@pageimport="java.util.*"%>
<%...@pageimport="java.text.*"%>
<%...@pageimport="java.io.*"%>
<%...@pageimport="com.sun.image.codec.jpeg.*"%>
<%...@pageimport="java.awt.image.*"%>
<%...@pageimport="java.awt.*"%>
<%...
Stringname=request.getParameter("name");
name=newString(name.getBytes("ISO-8859-1"));
Stringima=request.getParameter("image");
try{
Stringpath=request.getRealPath("/");
FileOutputStreamot=newFileOutputStream(path+name+".jpg");
//ServletOutputStreamot=response.getOutputStream();//也可以直接輸出顯示
FileInputStreamin=newFileInputStream(ima);
JPEGImageDecoderjpgCodec=JPEGCodec.createJPEGDecoder(in);
BufferedImageimage=jpgCodec.decodeAsBufferedImage();
JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(ot);
encoder.encode(image);
in.close();
ot.close();
out.print("JSP上傳圖片成功!<BR>");
//載入上傳成功的圖片
out.print("<IMGwidth=200height=200src='"+name+".jpg'/>");
}
catch(Exceptione)
{
System.out.print(e.toString());
}
%>
❽ Java jsp頁面的上傳按鈕
<input type="file" name="uploadify" id="file_upload" />
❾ 用jsp 怎樣實現文件上傳
你下載一個jspsmart組件,網上很容易下到,用法如下,這是我程序的相關片斷,供你參考: <%@ page import="com.jspsmart.upload.*" %>
<jsp:useBean id="mySmartUpload" scope="page" class="com.jspsmart.upload.SmartUpload" />
<% 
 String photoname="photoname";
 
// Variables
 int count=0;        // Initialization
 mySmartUpload.initialize(pageContext); // Upload 
 mySmartUpload.upload();
 
 for (int i=0;i<mySmartUpload.getFiles().getCount();i++){  // Retreive the current file
  com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(i);  // Save it only if this file exists
  if (!myFile.isMissing()) {
  java.util.Date thedate=new java.util.Date();
     java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss"); 
     photoname = df.format(thedate);
      photoname +="."+ myFile.getFileExt();
   myFile.saveAs("/docs/docimg/" + photoname);
   count ++;  } }
%>
<% String title="1";
 String author="1";
 String content="1";
 String pdatetime="1";
 String topic="1";
 String imgintro="1";
 String clkcount="1"; if(mySmartUpload.getRequest().getParameter("title")!=null){
 title=(String)mySmartUpload.getRequest().getParameter("title");
 title=new String(title.getBytes("gbk"),"ISO-8859-1");
 }
if(mySmartUpload.getRequest().getParameter("author")!=null){
 author=(String)mySmartUpload.getRequest().getParameter("author");
  author=new String(author.getBytes("gbk"),"ISO-8859-1");
 }
if(mySmartUpload.getRequest().getParameter("content")!=null){
 content=(String)mySmartUpload.getRequest().getParameter("content");
 content=new String(content.getBytes("gbk"),"ISO-8859-1");
 }
if(mySmartUpload.getRequest().getParameter("pdatetime")!=null){
 pdatetime=(String)mySmartUpload.getRequest().getParameter("pdatetime");
 }
if(mySmartUpload.getRequest().getParameter("topic")!=null){
 topic=(String)mySmartUpload.getRequest().getParameter("topic");
 }
 if(mySmartUpload.getRequest().getParameter("imgintro")!=null){
 imgintro=(String)mySmartUpload.getRequest().getParameter("imgintro");
 imgintro=new String(imgintro.getBytes("gbk"),"ISO-8859-1");
 }
if(mySmartUpload.getRequest().getParameter("clkcount")!=null){
 clkcount=(String)mySmartUpload.getRequest().getParameter("clkcount");
 }
//out.println(code+name+birthday);
 %>
❿ jsp上傳圖片,最好完整代碼。100分!
upfile.jsp 文件代碼如下:
<form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">     
<input type="file" name="file">     
<input type="submIT" name="sub" value="upload">     
 </form>  
  <form method="post" action="uploadimage.jsp" name="form1" enctype="multipart/form-data">
  <input type="file" name="file">
  <input type="submit" name="sub" value="upload">
   </form>
<STRONG><FONT color=#ff0000>uploadimage.jsp</FONT></STRONG> 
文件代碼如下:  
uploadimage.jsp
文件代碼如下:view plain to clipboardprint?
<PRE class=java name="code"><%@ page language="java"  pageEncoding="gb2312"%>     
<%@ page import="java.io.*,java.awt.Image,java.awt.image.*,com.sun.image.codec.jpeg.*,java.sql.*,com.jspsmart.upload.*,java.util.*"%>     
<%@ page import="mainClass.*" %>     
<html>     
  <head>     
    <title>My JSP 'uploadimage.jsp' starting page</title>     
  </head>   
  <body>     
    <%     
    SmartUpload sma=new SmartUpload();  
    long file_max_size=4000000;   
    String filename1="",ext="",testvar=""; 
    String url="uploadfiles/"; 
    sma.initialize(pageContext);   
    try    
    {     
    sma.setAllowedFilesList("jpg,gif");   
    sma.upload();   
    }catch(Exception e){     
    %>     
    <script language="jscript">     
    alert("只允許上傳jpg,gif圖片")    
    window.location.href="upfile.jsp"    
    </script>     
    <%     
    }     
    try{     
    com.jspsmart.upload.File myf=sma.getFiles().getFile(0);  
    if(myf.isMissing()){   
    %>     
    <script language="jscript">     
    alert("請選擇要上傳的文件!")     
    window.location.href="upfile.jsp"    
    </script>     
    <%     
    }else{   
    ext=myf.getFileExt();   
    int file_size=myf.getSize();   
    String saveurl="";   
    if(file_size < file_max_size){   
    Calendar cal=Calendar.getInstance();   
    String filename=String.valueOf(cal.getTimeInMillis());   
    saveurl=request.getRealPath("/")+url;  
    saveurl+=filename+"."+ext;   
    myf.saveAs(saveurl,sma.SAVE_PHYSICAL);   
    myclass mc=new myclass(request.getRealPath("data/data.mdb"));   
    mc.executeInsert("insert into [path] values('uploadfiles/"+filename+"."+ext+"')");
    out.println("圖片上傳成功!");   
    response.sendRedirect("showimg.jsp");  
    }   
    }   
    }catch(Exception e){     
    e.printStackTrace();     
    }     
    %>   
  </body>  
</html>   
</PRE>  
本文來自: IT知道網(http://www.itwis.com) 詳細出處參考:http://www.itwis.com/html/java/jsp/20080916/2409.html
