從JSP頁使圖片以JPEG編碼後儲存在指定檔案夾中。這種JSP上傳圖片方式與組件上傳相比似乎笨拙而又不能對檔案屬性進行操作,但的確可以輕鬆實現JSP上傳圖片的功能。
uploadimage1.jsp實現構建一個表單,提交用於為
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%><br /><%<br />String path = request.getContextPath();<br />String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";<br />%></p><p><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><br /><html><br /> <head><br /> <base href="<%=basePath%>"></p><p> <title>My JSP 'index.jsp' starting page</title><br /><meta http-equiv="pragma" content="no-cache"><br /><meta http-equiv="cache-control" content="no-cache"><br /><meta http-equiv="expires" content="0"><br /><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><br /><meta http-equiv="description" content="This is my page"><br /><!--<br /><link rel="stylesheet" type="text/css" href="styles.css" mce_href="styles.css"><br />--><br /> </head></p><p> <body><br /> This is my JSP page. <br><br /> <form action="MyJsp.jsp" method="post"><br /> :<INPUT TYPE="text" NAME="name"><BR><br />:<INPUT TYPE="file" NAME="image"><BR><br /><INPUT TYPE="submit" value="t"><br /> </form><br /> </body><br /></html><br />
圖片重新命名的參數,以及圖片檔案。
<%@ page contentType="text/html;charset=gb2312"%><br /><%@ page import="java.util.*"%><br /><%@ page import="java.text.*"%><br /><%@ page import="java.io.*"%><br /><%@ page import="com.sun.image.codec.jpeg.*"%><br /><%@ page import="java.awt.image.*"%><br /><%@ page import="java.awt.*"%> </p><p><%<br />String name=request.getParameter("name");<br />name=new String(name.getBytes("ISO-8859-1"));<br />String ima=request.getParameter("image");<br />out.print(name+"/n"+ima);<br />try{<br />String path=request.getRealPath("/");<br />FileOutputStream ot = new FileOutputStream(path+name+".jpg");<br />// ServletOutputStream ot=response.getOutputStream(); //也可以直接輸出顯示<br />FileInputStream in=new FileInputStream(ima);<br />JPEGImageDecoder jpgCodec = JPEGCodec.createJPEGDecoder(in);<br />BufferedImage image = jpgCodec.decodeAsBufferedImage();<br />JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(ot);<br />encoder.encode(image);<br />in.close();<br />ot.close();<br />out.print("JSP上傳圖片成功!<BR>");<br />//載入上傳成功的圖片<br />out.print("<IMG width=200 height=200 src=""+name+".jpg" mce_src=""+name+".jpg" />");<br />}<br />catch(Exception e)<br />{<br />System.out.print(e.toString());<br />}<br />%><br />
源地址:http://www.soft6.com/tech/16/169469.html