其他分享
首页 > 其他分享> > Servlet3.0上传图片

Servlet3.0上传图片

作者:互联网

一、前端JSP页面

<!DOCTYPE html>
<html>
	<head>
	<meta charset="UTF-8">
	<title>Servlet3.0文件上传</title>
	</head>
	<body>
		<h1>Servlet3.0文件上传</h1>
		<b id="msg" style="color: red;"></b>
				<form name="myform" action="upload" method="post" enctype="multipart/form-data">
				<table>
				<tr>
				<td>用户名:</td>
				<td><input type="text" name="username" /></td>
				</tr>
				<td>图片:</td>
				<td><input type="file" name="logo" /></td>
				</tr>
				<tr>
				<td colspan="2"><input type="submit" value="提交" /></td>
				</tr>
				</table>
		</form>
	</body>
</html>

二、后台逻辑处理的Servlet,需要导入文件上传处理包:commons-io -2.4.jar、commons -fileupload -1.3.1.jar

jar包地址:https://pan.baidu.com/s/1hcr_QOj7l3nuIlDA61EaaQ 密码:3uk4

import java.io.IOException;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload")
@MultipartConfig
public class FileUploadServlet1 extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
* Servlet3.0中,没有提供直接获取上传文件的文件名方法。需要使用如下方式来获取文件名
*/
protected String getFileName(Part part) {
	String fileName = null;
	String cotentDesc = part.getHeader("Content-Disposition");
	Pattern pattern = Pattern.compile("filename=\"(.+)\"");
	Matcher matcher = pattern.matcher(cotentDesc);
	if (matcher.find()) {
		fileName = matcher.group(1);
	}
	return fileName;
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	response.setContentType("text/html;charset=utf-8");
	String name = request.getParameter("username");
	Part part = request.getPart("logo");
	String fileName = this.getFileName(part); //调用获取文件名的方法
	String str = part.getName(); //前端jsp页面中指定的name属性的值,即<input type="file" name="logo" />中的logo
	System.out.println("用户名:" + name + "+ ",文件名:" + fileName + ",输入框名:" + str);
	String hzm = fileName.substring(fileName.indexOf("."));//获取文件的后缀名
	part.write("D:/ZhuoXun JavaWeb/Servlet3.x/WebContent/img/" + new Date().getTime() + hzm);//文件的保存位置
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

标签:Servlet3.0,String,上传,fileName,part,import,servlet,javax,图片
来源: https://blog.csdn.net/weixin_44578313/article/details/94855725