servlet接受form表单d值和文件上传

ApacheCommons组件  commons-fileupload-1.3.2.jar和commons-io_2.4.jar

Servlet页面

package com.studentweb.mode;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
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 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;

import com.studentweb.control.StudentUtil;

@SuppressWarnings("serial")
public class AddStudent extends HttpServlet {

	@SuppressWarnings("rawtypes")
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		StudentUtil showStudent = new StudentUtil();

		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload diskFileUpload = new ServletFileUpload(factory);
		diskFileUpload.setHeaderEncoding("utf-8");
		// 定义一个hashmap存放请求参数
		HashMap<String, String> parameters = new HashMap<String, String>();
		List paramItems = null;
		try {
			paramItems = diskFileUpload.parseRequest(request);

		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		Iterator i = paramItems.iterator();
		// 依次出来每个文件 请求参数
		while (i.hasNext()) {
			FileItem fi = (FileItem) i.next();
			if (!fi.isFormField()) {//判断是文件还是 value值
				String fileName = fi.getName();
				String savaFile = "images/" + fileName;
				String filePath = getServletContext().getRealPath("/")
						+ savaFile;
				File file = new File(filePath);
				try {
					fi.write(file);
				} catch (Exception e) {
					e.printStackTrace();
				}
				parameters.put("header_url", savaFile);
			} else {
				String name = fi.getFieldName();
				String value = null;
				try {
					value = fi.getString("utf-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				parameters.put(name, value);
			}
		}
		String name = parameters.get("name");
		String Age = parameters.get("age");
		String grade = parameters.get("grade");
		String gender = parameters.get("gender");
		String headerUrl = parameters.get("header_url");
		int age = Integer.parseInt(Age);
		boolean a = showStudent.SelectStudent(name);
		if (a) {
			response.sendRedirect("/StudentWebV_2.1/StudentThereare.html");
		} else {
			showStudent.addStudnet(grade, name, age, gender, headerUrl);
			response.sendRedirect("/StudentWebV_2.1/jump.html");
		}

	}
}
JSP 页面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/bootstrap.css" />
<style type="text/css">
body {
	font-size: 20px;
	padding-bottom: 40px;
	background-color: white;
}

.sidebar-nav {
	padding: 9px 0;
}

@media ( max-width : 980px) { /* Enable use of floated navbar text */
	.navbar-text.pull-right {
		float: none;
		padding-left: 5px;
		padding-right: 5px;
	}
}

.btn {
	position: absolute;
	top: 30%;
	left: 40%;
	color: blue;
	font-size: 20px;
}
</style>
<script type="text/javascript">
			function checkInput() {
				var name = document.form1.name1.value;
				var age = document.form1.age.value;
				var a =isNaN(age);
				if(name == "") {
					alert("请输入姓名!");
					return false;
				} else if(age == "") {
					alert("请输入年龄!");
					return false;
				} else if(a){
				alert("年龄有误!");
					return false;
				}else{
				return true;
				}
			}
		</script>
</head>

<body>
	<form name="form1" action="servlet/AddStudent" method="post"
		οnsubmit="return checkInput()" enctype="multipart/form-data">
		<table class="table table-bordered table-hover m10"
			style="margin-left:10px;margin-top:3px;">
			<tr>
				<td class="tableleft">姓名</td>
				<td><input type="text" name="name" /></td>
				<td class="tableleft">年龄</td>
				<td><input type="text" name="age" /></td>
			</tr>
			<br>
			<tr>
				<br>
				<td width="10%" class="tableleft">学生班级</td>
				<td><select name="grade">
						<option value='java' /> Java
						<option value='安卓' /> 安卓
				</select>
				<td width="10%" class="tableleft">学生性别</td>
				<td><select name="gender">
						<option value='男' /> 男
						<option value='女' /> 女
				</select> <br />头像: <input type="file" name="myfile" /><br> <input type="submit" value="提交" class="btn">
					</form>
</body>

</html>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
要在Web应用中实现文件上传,需要使用HTML中的表单(form)以及Java中的Servlet来完成。下面是实现文件上传的简单示例: 首先,在HTML中创建表单,设置"enctype"属性为"multipart/form-data",并添加一个文件选择框: ``` <form action="upload" method="POST" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="上传"> </form> ``` 然后,在Java中编写Servlet代码来处理上传的文件。通过获取HttpServletRequest对象,并调用其getParameter方法来获取上传的文件。最后,将上传的文件保存到指定的位置。 ``` @WebServlet("/upload") @MultipartConfig public class FileUploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Part filePart = request.getPart("file"); String fileName = getFileName(filePart); InputStream fileContent = filePart.getInputStream(); String savePath = "path/to/save/file/" + fileName; Files.copy(fileContent, Paths.get(savePath), StandardCopyOption.REPLACE_EXISTING); } private String getFileName(Part part) { String contentDisposition = part.getHeader("content-disposition"); String[] tokens = contentDisposition.split(";"); for (String token : tokens) { if (token.trim().startsWith("filename")) { return token.substring(token.indexOf("=") + 2, token.length() - 1); } } return ""; } } ``` 在上面的代码中,使用了@MultipartConfig注解来指示Servlet支持文件上传,并通过调用request.getPart方法获取上传的文件。最后,将文件保存到指定的位置。 需要注意的是,上传的文件大小可能比较大,需要设置合适的缓存大小。可以在web.xml文件中添加以下配置: ``` <multipart-config> <max-file-size>10485760</max-file-size> // 10MB <max-request-size>20971520</max-request-size> // 20MB <file-size-threshold>5242880</file-size-threshold> // 5MB </multipart-config> ``` 上面的配置设置了上传的文件最大为10MB,请求大小最大为20MB,缓存大小为5MB。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

茅十八呀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值