JavaServlet上传图⽚到指定⽂件夹并显⽰图⽚
在学习Servlet过程中,针对图⽚上传做了⼀个Demo,实现的功能是:在a页⾯上传图⽚,点击提交后,将图⽚保存到服务器指定路径(D:/image);跳转到b页⾯,b页⾯读取展⽰绝对路径(D:/image)的图⽚。主要步骤如下:
步骤⼀:上传页⾯uploadphoto.jsp
需要注意两个问题:
1.form 的method必须是post的,get不能上传⽂件,还需要加上enctype="multipart/form-data" 表⽰提交的数据是⼆进制⽂件。
2.需要提供type="file" 的字段进⾏上传
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>upload page</title>
</head>
<body >
<form action="uploadPhoto" method="post" enctype="multipart/form-data">
英雄名称: <input type="text" name="heroName" /> <br><br>
上传头像: <input type="file" name="filepath" /> <br><br>
<input type="submit" value="上传">
</form>
</body>
</html>
步骤⼆:UploadPhotoServlet类
1. 需要⽤到两个第三⽅的jar包,commons-io-1.4.jar和commons-fileupload-1.
2.2.jar。项⽬是Maven项⽬,直接在l⽂件中引⼊:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
javaservlet和jsp的比较<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
2. 前部分代码是固定写法,⽤来做⼀些准备⼯作。直到遍历出Item,⼀个Item就是对应⼀个浏览器提交的数据,通过
3. 客户提交的⽂件名有可能是⼀样的,所以在服务端保存⽂件的时候,不能使⽤客户提交的⽂件名。这⾥使⽤的是⼀种粗糙的解决⽂件名重复的办法,即使⽤时间戳。
package servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
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 org.apachemons.fileupload.FileItem;
import org.apachemons.fileupload.FileUploadException;
import org.apachemons.fileupload.disk.DiskFileItemFactory;
import org.apachemons.fileupload.servlet.ServletFileUpload;
public class UploadPhotoServlet extends HttpServlet {
public static String filename = null;
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServletResponse response){
}
@SuppressWarnings("rawtypes")
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException{
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
factory.setSizeThreshold(1024 * 1024);
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator iter = items.iterator();
while(iter.hasNext()){
FileItem item = (FileItem) ();
if(!item.isFormField()){
// 根据时间戳创建头像⽂件
filename = System.currentTimeMillis() + ".jpg";
System.out.ContextPath());
/*File f = new File(getServletContext().getRealPath("upload"));*/
File f = new File("D://image");
if (!f.exists()) {
f.mkdir();
}
String imgsrc = f + "/" + filename;
// 复制⽂件
InputStream is = InputStream();
FileOutputStream fos = new FileOutputStream(imgsrc);
byte b[] = new byte[1024 * 1024];
int length = 0;
while (-1 != (length = is.read(b))) {
fos.write(b, 0, length);
}
fos.flush();
fos.close();
}else {
System.out.FieldName());
String value = String();
value = new Bytes("ISO-8859-1"), "UTF-8");
System.out.println(value);
}
}
//request.setAttribute("filename", filename);
//RequestDispatcher("/showPhoto").forward(request, response);
response.sendRedirect("/ServletTest/showPhoto?filename="+filename);
}
}
步骤三:ShowPhotoServlet类
其实这个类可以省略,即可以直接在UploadPhotoServlet类中跳转到页⾯showphoto.jsp,但是为了学习Servlet跳转⽅⾯的知识,于是增加⼀个新的Servlet类。
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowPhotoServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
String filename = Parameter("filename").toString();
response.sendRedirect("/ServletTest/showphoto.jsp?filename="+filename);
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
String filename = Attribute("filename").toString();
request.setAttribute("filename", filename);
}
}
1.servlet跳转⾄jsp(注意)
a.服务端跳转浏览器的地址不变(请求转发)
request.setAttribute("filename", filename);
RequestDispatcher("/showphoto.jsp").forward(request, response);
b.客户端跳转浏览器的地址发⽣变化(请求重定向)
response.sendRedirect("/ServletTest/showphoto.jsp?filename="+filename);
2.servlet跳转⾄另⼀个servlet
a.服务端跳转需要重写doPost以获取传递参数
String filename = Attribute("filename").toString();
b.客户端跳转需要重写doGet以获取传递参数
String filename = Parameter("filename").toString();
步骤三:l配置
<servlet>
<servlet-name>UploadPhotoServlet</servlet-name>
<servlet-class>servlet.UploadPhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadPhotoServlet</servlet-name>
<url-pattern>/uploadPhoto</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ShowPhotoServlet</servlet-name>
<servlet-class>servlet.ShowPhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowPhotoServlet</servlet-name>
<url-pattern>/showPhoto</url-pattern>
</servlet-mapping>
步骤四:展⽰页⾯showphoto.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "/TR/html4/loose.dtd"> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Image page</title>
</head>
<body>
<%
String filename = Parameter("filename");
String srcimg = "/image/"+filename;
%>
<img src="<%=srcimg%>"/>
</body>
</html>
1.配置虚拟路径
解决办法:
使⽤虚拟路径来配置,在tomcat下的l中增加⼀个代码在<Host></Host>中间: <Context docBase="D:\image" path="/image" reloadable="true"/>
然后在JSP页⾯中<img src = "/image/(图⽚名)">就可以访问图⽚了。
最终实现效果:
上传界⾯:
展⽰界⾯:
保存图⽚的⽂件夹:
总结
以上所述是⼩编给⼤家介绍的通过Java Servlet图⽚上传⾄指定⽂件夹并显⽰图⽚,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。在此也⾮常感谢⼤家对⽹站的⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论