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我!!