JSP 页面上传图片 提交到servlet控制层 如何实现 30
3个回答
展开全部
JSP:
<%@ page language="java" pageEncoding="GBK" %>
<%@ page import="cn.edu.bit.business.*,java.util.*,cn.edu.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.edu.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.edu.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要注意相对路径的设定方法,如有其它问题,可以追问...希望能帮到你
<%@ page language="java" pageEncoding="GBK" %>
<%@ page import="cn.edu.bit.business.*,java.util.*,cn.edu.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.edu.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.edu.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要注意相对路径的设定方法,如有其它问题,可以追问...希望能帮到你
展开全部
额··
看一楼写了那么长 我都不好意思回答了··
不过丢个东西给你吧··
下面是上传所有文件到服务器的代码 写在servlet中:
//保存文件到服务器中
String fileName = null;
response.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);//文件大小的限制 最大不能超过4096K
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
fileName = item.getName();
System.out.println(fileName + "wwwwwwww");
item.write(new File(uploadPath + fileName));
截取了一部分 不过相信你能懂的
看一楼写了那么长 我都不好意思回答了··
不过丢个东西给你吧··
下面是上传所有文件到服务器的代码 写在servlet中:
//保存文件到服务器中
String fileName = null;
response.setContentType("text/html; charset=UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4096);//文件大小的限制 最大不能超过4096K
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxPostSize);
List fileItems = upload.parseRequest(request);
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
fileName = item.getName();
System.out.println(fileName + "wwwwwwww");
item.write(new File(uploadPath + fileName));
截取了一部分 不过相信你能懂的
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
<%@page contentType="image/JPEG" import="java.awt.*,java.awt.image.*,java.util.*,javax.imageio.*"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%!Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}%>
<%
//out.clear();//????resin???????tomacat??????
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(10);
int yl = random.nextInt(10);
g.drawLine(x, y, x + xl, y + yl);
}
char c[] = new char[62];
for (int i = 97, j = 0; i < 123; i++, j++) {
c[j] = (char) i;
}
for (int o = 65, p = 26; o < 91; o++, p++) {
c[p] = (char) o;
}
for (int m = 48, n = 52; m < 58; m++, n++) {
c[n] = (char) m;
}
String sRand = "";
for (int i = 0; i < 4; i++) {
int x = random.nextInt(62);
String rand = String.valueOf(c[x]);
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
// ??????SESSION
session.setAttribute("rand", sRand);
System.out.println(sRand);
g.dispose();
ImageIO.setUseCache(true);
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
我以前写的,你试试
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%!Color getRandColor(int fc, int bc) {
Random random = new Random();
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}%>
<%
//out.clear();//????resin???????tomacat??????
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
int width = 60, height = 20;
BufferedImage image = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
Random random = new Random();
g.setColor(getRandColor(200, 250));
g.fillRect(0, 0, width, height);
g.setFont(new Font("Times New Roman", Font.PLAIN, 18));
g.setColor(getRandColor(160, 200));
for (int i = 0; i < 155; i++) {
int x = random.nextInt(width);
int y = random.nextInt(height);
int xl = random.nextInt(10);
int yl = random.nextInt(10);
g.drawLine(x, y, x + xl, y + yl);
}
char c[] = new char[62];
for (int i = 97, j = 0; i < 123; i++, j++) {
c[j] = (char) i;
}
for (int o = 65, p = 26; o < 91; o++, p++) {
c[p] = (char) o;
}
for (int m = 48, n = 52; m < 58; m++, n++) {
c[n] = (char) m;
}
String sRand = "";
for (int i = 0; i < 4; i++) {
int x = random.nextInt(62);
String rand = String.valueOf(c[x]);
sRand += rand;
g.setColor(new Color(20 + random.nextInt(110), 20 + random
.nextInt(110), 20 + random.nextInt(110)));
g.drawString(rand, 13 * i + 6, 16);
}
// ??????SESSION
session.setAttribute("rand", sRand);
System.out.println(sRand);
g.dispose();
ImageIO.setUseCache(true);
ImageIO.write(image, "JPEG", response.getOutputStream());
%>
我以前写的,你试试
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询