HttpServlet图片上传至指定目录

  • Post author:
  • Post category:其他


1.lib下的两个jar包

commons-fileupload-1.3.1.jar

commons-io-2.2.jar

2.web.xml

	<servlet>
		<servlet-name>imageUploadServlet</servlet-name>
		<servlet-class>com.disease.servlet.imageUploadServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>imageUploadServlet</servlet-name>
		<url-pattern>/imageUploadServlet</url-pattern>
	</servlet-mapping>

3.java代码

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.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;


@SuppressWarnings("serial")
public class UploadServlet extends HttpServlet {
	public static String filename = null;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
	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;
		String picPath = "";
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		Iterator iter = items.iterator();
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();
			if (!item.isFormField()) {
				// 根据时间戳创建头像文件
				filename = System.currentTimeMillis() + ".jpg";
				System.out.println(request.getContextPath());
				/*
				 * File f = new File(getServletContext().getRealPath("upload"));
				 */
				// D盘的存放文件夹
				File f = new File("D://reports");
				if (!f.exists()) {
					f.mkdir();
				}
				String imgsrc = f + "/" + filename;
				// /reports/1551435783395.jpg
				picPath = "/reports/" + filename;
				// 复制文件
				InputStream is = item.getInputStream();
				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.println(item.getFieldName());
				String value = item.getString();
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
				System.out.println(value);
			}
		}
		request.setAttribute("picPath", picPath);
		String msg = "上传成功";
		request.setAttribute("msg", msg);
		request.getRequestDispatcher("./jsp/editUserIll.jsp").forward(request,response); 
	}

}

4.前端上传

<form action="UploadServlet" method="post"
	enctype="multipart/form-data">
	<br />
	<table class="btm">
		<tbody>
			<tr>
				<td><span></span></td>
				<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;选择图片</td>
				<td><input type="file" name="filepath" /></td>
			</tr>

		</tbody>
	</table>
	<div style="top: 286px; display: none;" id="q_Msgbox"
		class="zeng_msgbox_layer_wrap">
		<span class="zeng_msgbox_layer" style="z-index: 10000;"
			id="mode_tips_v2"><span class="gtl_ico_succ"></span>设置成功!<span
			class="gtl_end"></span></span>
	</div>
	<div class="zeng_msgbox_layer_wrap" id="q_Msgbox"
		style="display: block"></div>
	<br />
	<table>
		<tbody>


			<tr>
				<td width="25"></td>
				<td colspan="2"><input type="submit" value="上传"
					id="save" name="save" class="btn_32"></td>
			</tr>
		</tbody>
	</table>
</form>

5.前端图片显示

<div class="imgDiv">
<p />
<img src=<%=picStr[i]%> width="90%" /> 
<p />
</div>

6.数据库存放路径

/reports/1551880035692.jpg

7.tomcat虚拟路径配置





tomcat


下的


server.xml


中增加一个代码





<Host></Host>


中间:

<Context path="/reports" docBase="D:/reports" debug="0" reloadable="true"/>

若使用eclipse


然后在


JSP


页面中


<img src = “/


reports


/(


图片名


)”>


就可以访问图片了


参考自:

http://www.cnblogs.com/gccbuaa/p/7226139.html

附:

项目大致目录

参考网址:


https://www.jb51.net/article/120299.htm



版权声明:本文为yks0527原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。