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;
}
}
2. 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
3. jsp+servlet 上傳圖片並顯示出來
其實你這個擋也顯示圖片其實很簡單的,
你的需求無非是兩個
1.servlet上傳文件(圖片)
2.點擊 瀏覽 圖標,然後選擇圖片文件,然後就可以在頁面中的某個地方看到圖片
是這兩個需求么?
首先說第二個吧。
你上傳圖片之後,就馬上觸發js函數,內容為
var PicPath = document.getElementById("yourfile").value;
document.getElementById("yourDiv").innerHTML="<IMG src="+PicPath+"/>";
OK了
第一個嘛就無所謂說了,不過我還是貼一個代碼吧,
public void upLoadFile(HttpServletRequest request, HttpServletResponse response) {
PrintWriter out = null;
response.setCharacterEncoding("UTF-8");
//實例化文件工廠
FileItemFactory factory = new DiskFileItemFactory();
//配置上傳組件ServletFileUpload
ServletFileUpload upload = new ServletFileUpload(factory);
try {
out = response.getWriter();
//從request得到所有上傳域的列表
List<FileItem> list = upload.parseRequest(request);
for (FileItem item : list) {
//isFormField判斷一個item類對象封裝的是一個普通的表單欄位還是文件表單欄位。
// 如果item是文件域,則做出如下處理:
if (!item.isFormField()) {
//上傳文件域的Name
String fileName = item.getName();
//截取擴展名
int idx = fileName.lastIndexOf(".");
String extension = fileName.substring(idx);
//獲取文件名
String name = new Date().getTime() + extension;
//得到文件夾的物理路徑
String path = this.getServletContext().getRealPath("\\upload");
//創建一個File
File file = new File(path + "\\" + name);
FileOutputStream o = new FileOutputStream(file);
InputStream in = item.getInputStream();
try {
LoadProcessServlet.process = 0;
LoadProcessServlet.total = 100;
LoadProcessServlet.isEnd = false;
LoadProcessServlet.total = item.getSize();
byte b[] = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
LoadProcessServlet.process+=n;
o.write(b, 0, n);
System.out.println("實際:"+LoadProcessServlet.process);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
LoadProcessServlet.isEnd = true;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
4. JSP 頁面上傳圖片 提交到servlet控制層 如何實現
JSP:
<%@ page language="java" pageEncoding="GBK" %>
<%@ page import="cn.e.bit.business.*,java.util.*,cn.e.bit.Object.*,com.jspsmart.upload.*" errorPage="error.jsp"%>
<%-- page import="org.apache.commons.fileupload.*;" --%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>Lomboz JSP</title>
<style type="text/css">
<!--
@import url("../../css/OSX.css");
-->
</style>
</head>
<SCRIPT language=javascript>
function CheckForm()
{
if(document.add_student_Form.name.value=="")
{
alert("請輸入姓名!");
return false;
}
if(document.add_student_Form.image.value=="")
{
alert("請上傳圖片!");
return false;
}
document.add_student_Form.submit();
if(document.add_student_Form.advisor.value=="")
{
alert("暫時沒有指導老師,無法創建學生!");
return false;
}
document.add_student_Form.submit();
}
</SCRIPT>
<body bgcolor="#CAD7F7" topmargin="100">
<%
ArrayList gl = (ArrayList)Grade_Manager.getGradeList();
ArrayList Tl = (ArrayList)Teacher_Manager.getTeacherList2();
%>
<div align="center">
<form name="add_student_Form" method="post" enctype="multipart/form-data" action="<%=basePath %>/add_student">
<table width="500" border="0" cellspacing="1" cellpadding="1" class="tableBorder">
<tr>
<td colspan="2" align="center" background="../../images/guanli/admin_bg_1.gif" class="whitenormal">添加學生</td>
</tr>
<tr>
<td width="97" align="center" bgcolor="F1F3F5" class="normalText">姓名:</td>
<td width="396" bgcolor="F1F3F5"><input name="name" type="text" id="name" class="textBox"></td>
</tr>
<tr>
<td align="center" bgcolor="F1F3F5" class="normalText">性別:</td>
<td bgcolor="F1F3F5"><input type="radio" name="radiobutton" value="male" checked/>
<span class="normalText">男</span> <input type="radio" name="radiobutton" value="female" />
<span class="normalText">女</span></td>
</tr>
<tr>
<td align="center" bgcolor="F1F3F5" class="normalText">年級:</td>
<td bgcolor="F1F3F5">
<select name="grade">
<%
Iterator iter = gl.iterator();
while(iter.hasNext())
{
Grade grade = (Grade)iter.next();
%>
<option value="<%=grade.getId()%>" ><%=grade.getName()%></option>
<%
}
%>
</select>
</td>
</tr>
<tr>
<td align="center" bgcolor="F1F3F5" class="normalText">指導老師:</td>
<td bgcolor="F1F3F5">
<select name="advisor" class="textBox">
<%
Iterator it = Tl.iterator();
while(it.hasNext())
{
Teacher teacher = (Teacher)it.next();
%>
<option value="<%=teacher.getTeacher_id()%>" ><%=teacher.getTeacher_name()%></option>
<%
}
%>
</select>
</td>
</tr>
<tr>
<td align="center" bgcolor="F1F3F5" class="normalText">圖片:</td>
<td bgcolor="F1F3F5"><input type="file" name="image">
</td>
</tr>
<tr align="center">
<td colspan="2" bgcolor="F1F3F5"><input type="button" name="Submit" value="提交" onClick="CheckForm()"> </td>
</tr>
</table>
</form>
</div>
</body>
</html>
其中只有圖片上傳的,你還要下載一個jspsmart.jar或者jspSmartUpload.jar組件
Servlet:
package cn.e.bit.servlet;
import java.io.*;
import java.util.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.jspsmart.upload.*;
import cn.e.bit.business.Student_Manager;
/**
*
* @EricWong
*2007-7-21
*/
public class AddStudentServlet extends HttpServlet{
private ServletConfig config;
String image;
final public void init(ServletConfig config) throws ServletException {
this.config = config;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("guanli/student/login.jsp");
requestDispatcher.forward(request,response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
HttpSession ses = request.getSession();
try{
SmartUpload su =new SmartUpload();
String ext = "";
su.initialize(config, request, response);
su.setAllowedFilesList("jpg,gif");
su.upload();
com.jspsmart.upload.Files file = su.getFiles();
image = (String)file.getFile(0).getFileName();
Calendar calendar = Calendar.getInstance();
String filename = String.valueOf(calendar.getTimeInMillis());
int index = image.indexOf(".");
image = image.replace(image.substring(0, index), filename);
System.out.println(image);
su.getFiles().getFile(0).saveAs("./images/student_image/" + image ,su.SAVE_VIRTUAL);
String name = su.getRequest().getParameter("name");
int advisor = Integer.parseInt(su.getRequest().getParameter("advisor"));
String sex = (String)su.getRequest().getParameter("radiobutton");
String grade = (String)su.getRequest().getParameter("grade");
int grade_id = Integer.parseInt(grade);
Student_Manager.Add_Student(name,grade_id,image,sex,advisor);
}
catch(Exception e){
System.out.println("fail");
e.printStackTrace();
}
RequestDispatcher requestDispatcher = request.getRequestDispatcher("guanli/student/add_success1.jsp");
requestDispatcher.forward(request,response);
}
}
我是把相應的圖片先改名再存入伺服器,防止重名,而且LZ要注意相對路徑的設定方法,如有其它問題,可以追問...希望能幫到你
5. 在jsp中做照片上傳預覽的代碼
建議你使用 Web upload 組件,可圖片預覽, 可多選,可拖放上傳,可粘貼後直接上傳
網路開源產品.
倆三行代碼就可以直接使用
具體網址 :
http://www.admin10000.com/document/4721.html
6. Java在jsp中 如何上傳圖片 在上傳時可以取到圖片大小並修改
用第三方工具去取 common-upload,具體取到圖片的方法參考代碼如下:
FileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
upload.setHeaderEncoding("utf-8");
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem fileItem : items) {
System.out.println("fileName=" + fileItem.getFieldName());
//獲取文件流
InputStream in = fileItem.getInputStream();
ServletContext context = getServletConfig().getServletContext();
String path = context.getRealPath("image");
System.out.println(path);
OutputStream out = new FileOutputStream(new File(path + "\\" + fileItem.getName()));
byte[] buffer = new byte[1024];
int len = 0;
while((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
System.out.println("寫入完畢");
}
} catch (FileUploadException e) {
e.printStackTrace();
}
7. 怎麼樣在jsp頁面上傳圖片把圖片的名字如1.jpg上傳到資料庫,把圖片保存到一個制定的文件夾裡面。
在JSP頁面中用"<input type="file"/> "然後用form提交到後台 得到文件名然後在servlet裡面用輸入輸出流不就可以了。
8. 求:用純jsp頁面上傳文件的代碼(不用其它組件)
FileInputStream fis = new FileInputStream(new File(url));
這個InputStream不是這樣拿的啊,new File(url) 的意思是讀取"url"這個文件,在自己機器上當然可以,遠程當然不行了,比如我機器上要傳個文件到你的伺服器,你new File("D:\\image\\a.jpg");你說能拿到我D盤上的圖片嗎?
另外:byte[] b = new byte[256]; 假如我的圖片有1M,你這個b數組怎麼可能裝的下呢!!應該正確拿到FileInputStream,然後byte[] b = new byte[fis.available()];
既然你用struts,那就用struts來拿:
<input type="file" name="picurl" />
注意這里:
<form action="picurlupload.do" method="post" enctype="multipart/form-data">//一定要enctype="multipart/form-data"
寫個Form:
PicurlForm ,只有一個FormFile類型的屬性:private FormFile picurl;生成get、set
寫個Action,PicurlUploadAction ,只要在execute方法里調用:
① PicurlForm ff = (PicurlForm)form;
② FormFile picurl = ff.getPicurl();
③ FileOutputStream fos = new FileOutputStream(load + "images/pic/" + fileName);
④ fos.write(picurl.getFileData());
就搞定了!!
剛好這邊有些寫好的文件上傳代碼,樓主需要的話可以M我!!