FORM的ENCTYPE="multipart/form-data" 时request.getParameter()值为null问题的解决

本文介绍了在处理使用multipart/form-data编码的表单上传问题时,如何通过不同方法获取除文件外的参数值。包括使用特定的组件如SmartUpload,解析multipart请求,以及在文件上传后接收参数。文章提供了实操示例,包括表单的设置、后台处理逻辑和解决乱码的方法。

解决当FORM的ENCTYPE="multipart/form-data" 时request.getParameter()获取不到值的方法

url:http://blog.youkuaiyun.com/georgejin/archive/2007/07/25/1706647.aspx


今天在原来上传文件页面的基础上,想添加一段文件的简介

因为同时要上传文件,所以ENCTYPE="multipart/form-data" 必须要加在form里面

可是这样的话,我再servlet里面用request.getParameter()方法无论如何都只是获得null值,

不是一般的郁闷,百度了一下,有人出现了同样的问题可是它用的是jspsmartupload组件实现文件上传的,

而我用的commons fileupload组件,仔细看了一下这个组件的api,可是英语太差了,没有发现相关的信息

我又尝试用session传递参数,可是发现有点麻烦,因为在表单提交之时你就得赋给session表单上它的数值,

这似乎要javascript,可是偶也不会,

后来只有google了,搜索了一些中文网页,也没有找到资料,试试不限制语言,呵呵呵,一大片,后来被俺发

现了这个

I cannot read the submitter using request.getParameter("submitter") (it returns null). ]

Situation:javax.servlet.HttpServletRequest.getParameter(String) returns null when the ContentType is multipart/form-data

Solutions:

Solution A:1. download http://www.servlets.com/cos/index.html2 . invoke getParameters() on com.oreilly.servlet.MultipartRequest

Solution B:1. download http://jakarta.apache.org/commons/sandbox/fileupload/2 . invoke readHeaders() in org.apache.commons.fileupload.MultipartStream

Solution C:1. download http://users.boone.net/wbrameld/multipartformdata/2 . invoke getParameter on com.bigfoot.bugar.servlet.http.MultipartFormData

Solution D:Use Struts. Struts 1.1 handles this automatically.说是不详细,接着往下看,另一种解决方法>


Solution B:
> 1. download > http://jakarta.apache.org/commons/sandbox/fileupload/
> 2. invoke readHeaders() in
> org.apache.commons.fileupload.MultipartStream

The Solution B as given by my dear friend is a bit hectic and a bit complex :(
We can try the following solution which I found much simpler (at least in usage).

1. Download one of the versions of UploadFile from http://jakarta.apache.org/commons/fileupload/
2. Invoke parseRequest(request) on org.apache.commons.fileupload.FileUploadBase which returns list of org.apache.commons.fileupload.FileItem objects.
3. Invoke isFormField() on each of the FileItem objects. This determines whether the file item is a form paramater or stream of uploaded file.
4. Invoke getFieldName() to get parameter name and getString() to get parameter value on FileItem if it's a form parameter. Invoke write(java.io.File) on FileItem to save the uploaded file stream to a file if the FileItem is not a form parameter.


还有一种方法就是使用jspsmartupload表单中enctype="multipart/form-data"的意思,是设置 表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了 multipart/form-data,才能完整的传递文件数据

但是设置了 enctype="multipart/form-data" ,除了file类型表单能获取到,其他value通过request.getParameter都得不到。这种情况下我们可以利用组件来解决该问题,例如用 jspsmartupload组件

com.jspsmart.upload.SmartUpload su = new com.jspsmart.upload.SmartUpload();
su.initialize(pageContext);
su.service(request, response);
su.setTotalMaxFileSize(100000000);
su.setAllowedFilesList("zip,rar");
su.setDeniedFilesList("exe,bat,jsp,htm,html,,");
su.upload();

String Name = su.getRequest().getParameter("Name");
String TYPE_ID = su.getRequest().getParameter("Type");

通过 su.getRequest().getParameter("value");就可以了,su.upload()好象必须放在前面,测试中将su.upload()放在获取参数后面不成功。


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/georgejin/archive/2007/07/25/1706647.aspx

关于用jspSmartUpload控件上传文件并附带参数的吐血体验

url:http://blog.youkuaiyun.com/thinker28754/archive/2007/05/26/1626844.aspx


用于上传数据的表单:

<form name="form1" method="post" action="servlet/Upfile" enctype="multipart/form-data">
<p>请输入手机号</p>
<p>
<input type="text" name="phone" value="1234567890"/>
</p>
<p>图片上传(仅现于*.gif和*.jpg文件)</p>
<p>
<input type="file" name="file1"/>
</p>


<p>
<input type="submit" name="submit" value="· 提交 ·"/>
</p>
</form>

提交的后台的servlet

SmartUpload su =new SmartUpload();

su.initialize(this.getServletConfig(), request, response);

String realPath = this.getServletContext().getRealPath("");
String path=realPath+"/images";

su.setAllowedFilesList("gif,jpg");
su.upload();
int count=su.save(path);

msdnid=su.getRequest().getParameter("phone");//注意这是接收表单传过来的参数
System.out.println("msdnid="+msdnid);

////////////////////////////////////////////////////////////////////////////////////////////////////////////////

特别说明:用于接收表单参数的语句一定要放在su.upload();语句的后面,也就是说要在文件上传后再接收,否则

不管你怎么试接收到的结果总是"null".

这是我在苦苦试了一天在晕到前的2分钟试出来的,真的不容易呀!!!!!

在上述问题得到解决后,当所传的参数为汉字时则接收到的全是乱码,经过反复实验将表单页面的编码格式设成"gb2312"就解决了这个问题.


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/thinker28754/archive/2007/05/26/1626844.aspx

解决当FORM的ENCTYPE="multipart/form-data" 时获取不到其它参数值的方法 ?
url:http://blog.youkuaiyun.com/heitu278/archive/2008/09/04/2882346.aspx


前提:使用 commons-fileupload-1.1.jar

UploadListener listener = new UploadListener(request, 0);
// Create a factory for disk-based file items
FileItemFactory factory = new MonitoredDiskFileItemFactory(listener);

// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);

try
{
// process uploads ..
List fileItems=upload.parseRequest(request);
Iterator iter = fileItems.iterator(); // 依次处理每个控件
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();// 忽略其他是文件域的所有表单信息
if (item.isFormField()){
out.println(item.getFieldName()+"="+item.getString()); 获得表单数据
}
}
}catch (FileUploadException e){
e.printStackTrace();
}

本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/heitu278/archive/2008/09/04/2882346.aspx

表单form的enctype="multipart/form-data"使用体会 收藏
在使用表单传送数据的时候,如果form 加了enctype="multipart/form-data" 这个属性,那么表单请求传到另一个jsp或servlet 里时
是不能用request.getParameter()来获取到各个表单元素的值的。
可以通用这样(上传组件提供的API):
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
// Create a factory for disk-based file items
org.apache.commons.fileupload.FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Parse the request
List /* FileItem */items = upload.parseRequest(request);
// Process the uploaded items
Iterator iter = items.iterator();

while (iter.hasNext()) {
org.apache.commons.fileupload.FileItem item = (org.apache.commons.fileupload.FileItem) iter
.next();
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("GBK");
//out.println(name + "=" + value);
params.put(name.toUpperCase(), value.trim());
} ......
===============================================================================
使用multipart/form-data上传时,发送的请求和一般的http不一样,需要转化后才能读其他参数。

如果你用spring,它提供一个MultiRequestResolver,只需要:
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
然后就能正常读取参数:
multipartRequest.getParameter("xxx");

以下是spring的处理方法,必须首先安装commons-fileupload组件:

public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
DiskFileUpload fileUpload = this.fileUpload;
String enc = determineEncoding(request);

// use prototype FileUpload instance if the request specifies
// its own encoding that does not match the default encoding
if (!enc.equals(this.defaultEncoding)) {
fileUpload = new DiskFileUpload();
fileUpload.setSizeMax(this.fileUpload.getSizeMax());
fileUpload.setSizeThreshold(this.fileUpload.getSizeThreshold());
fileUpload.setRepositoryPath(this.fileUpload.getRepositoryPath());
fileUpload.setHeaderEncoding(enc);
}

try {
List fileItems = fileUpload.parseRequest(request);
Map parameters = new HashMap();
Map multipartFiles = new HashMap();
for (Iterator it = fileItems.iterator(); it.hasNext();) {
FileItem fileItem = (FileItem) it.next();
if (fileItem.isFormField()) {
String value = null;
try {
value = fileItem.getString(enc);
}
catch (UnsupportedEncodingException ex) {
logger.warn("Could not decode multipart item '" + fileItem.getFieldName() +
"' with encoding '" + enc + "': using platform default");
value = fileItem.getString();
}
String[] curParam = (String[]) parameters.get(fileItem.getFieldName());
if (curParam == null) {
// simple form field
parameters.put(fileItem.getFieldName(), new String[] { value });
}
else {
// array of simple form fields
String[] newParam = StringUtils.addStringToArray(curParam, value);
parameters.put(fileItem.getFieldName(), newParam);
}
}
else {
// multipart file field
CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
multipartFiles.put(file.getName(), file);
if (logger.isDebugEnabled()) {
logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() +
" bytes with original filename [" + file.getOriginalFilename() + "], stored " +
file.getStorageDescription());
}
}
}
/***** 注意 parameters 就是普通的text之类的字段的值 *****/
return new DefaultMultipartHttpServletRequest(request, multipartFiles, parameters);
}
catch (FileUploadBase.SizeLimitExceededException ex) {
throw new MaxUploadSizeExceededException(this.fileUpload.getSizeMax(), ex);
}
catch (FileUploadException ex) {
throw new MultipartException("Could not parse multipart request", ex);
}
}
====================================================================================================
<form name="userInfo" method="post" action="first_submit.jsp" ENCTYPE="multipart/form-data">
表单标签中设置enctype="multipart/form-data"来确保匿名上载文件的正确编码。
如下:
<tr>
<td height="30" align="right">上传企业营业执照图片:</td>
<td><INPUT TYPE="FILE" NAME="uploadfile" SIZE="34" ></td>
</tr>
就得加ENCTYPE="multipart/form-data"。
表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form- data,才能完整的传递文件数据,进行下面的操作.
enctype=/"multipart/form-data/"是上传二进制数据; form里面的input的值以2进制的方式传过去。
form里面的input的值以2进制的方式传过去,所以request就得不到值了。 也就是说加了这段代码,用request就会传递不成功
,
取表单值加入数据库时,用到下面的:
SmartUpload su = new SmartUpload();//新建一个SmartUpload对象
su.getRequest().getParameterValues();取数组值
su.getRequest().getParameter( );取单个参数单个值


本文来自优快云博客,转载请标明出处:http://blog.youkuaiyun.com/aaaaatiger/archive/2009/06/16/4271009.aspx

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="java.sql.*" %> <%@ page import="com.yourproject.util.FileUploadUtil" %> <%@ page import="jakarta.servlet.http.Part" %> <%@ include file="db.jsp" %> <%! // 辅助方法:安全解析数 private Integer safeParseInt(String value) { if (value == null || value.trim().isEmpty()) return null; try { return Integer.parseInt(value.trim()); } catch (NumberFormatException e) { return null; } } private Double safeParseDouble(String value) { if (value == null || value.trim().isEmpty()) return null; try { return Double.parseDouble(value.trim()); } catch (NumberFormatException e) { return null; } } %> <% // ====================== 功能处理部分 ====================== String action = request.getParameter("action"); String currentTab = request.getParameter("currentTab") != null ? request.getParameter("currentTab") : "pet-management"; String message = null; String messageType = null; // 获取宠物信息(编辑模式) String title = null; Integer category = null; String tag = null; String photo = null; Double price = null; Integer stock = null; String descs = null; // 宠物描述 String petId = null; if ("edit".equals(action)) { petId = request.getParameter("id"); if (petId != null && !petId.isEmpty()) { try (PreparedStatement stmt = conn.prepareStatement("SELECT * FROM pets WHERE id = ?")) { stmt.setInt(1, Integer.parseInt(petId)); ResultSet rs = stmt.executeQuery(); if (rs.next()) { title = rs.getString("title"); category = rs.getInt("category"); tag = rs.getString("tag"); photo = rs.getString("photo"); price = rs.getDouble("price"); stock = rs.getInt("stock"); descs = rs.getString("descs"); } } catch (NumberFormatException | SQLException e) { message = "加载宠物信息失败: " + e.getMessage(); messageType = "error"; e.printStackTrace(); } } } // 处理表单提交(支持文件上传) if ("POST".equals(request.getMethod())) { // 获取普通表单字段 petId = request.getParameter("pet-id"); title = request.getParameter("pet-name"); String categoryStr = request.getParameter("pet-category"); tag = request.getParameter("pet-tags"); String priceStr = request.getParameter("pet-price"); String stockStr = request.getParameter("pet-stock"); descs = request.getParameter("pet-description"); // 对应表单里的name="pet-description" // 调试输出 System.out.println("Form Data:"); System.out.println("title: " + title); System.out.println("category: " + categoryStr); System.out.println("price: " + priceStr); System.out.println("stock: " + stockStr); System.out.println("descs: " + descs); // 解析数字段 Integer categoryInt = safeParseInt(categoryStr); Double priceDbl = safeParseDouble(priceStr); Integer stockInt = safeParseInt(stockStr); // 验证必需字段 if (title == null || title.trim().isEmpty()) { message = "请填写宠物名称"; messageType = "error"; } else if (categoryInt == null) { message = "请选择分类"; messageType = "error"; } else if (priceDbl == null || priceDbl <= 0) { message = "请输入有效的价格"; messageType = "error"; } else if (stockInt == null || stockInt < 0) { message = "请输入有效的库存数量"; messageType = "error"; } else if (descs == null || descs.trim().isEmpty()) { // 校验宠物描述 message = "请填写宠物描述"; messageType = "error"; } else { try { // 处理文件上传 Part filePart = request.getPart("pet-photo-file"); String existingPhoto = request.getParameter("existing-photo"); String newPhoto = null; if (filePart != null && filePart.getSize() > 0) { // 上传新图片 String contextPath = request.getServletContext().getRealPath("/"); newPhoto = FileUploadUtil.uploadImage(filePart, contextPath); // 删除旧图片(编辑模式且存在旧图片) if ("edit".equals(action) && existingPhoto != null && !existingPhoto.isEmpty()) { FileUploadUtil.deleteImage(existingPhoto, contextPath); } } // 确定使用的照片URL String finalPhoto = (newPhoto != null) ? newPhoto : existingPhoto; if ("add".equals(action)) { // 添加新宠物 String sql = "INSERT INTO pets (category, title, tag, photo, price, stock, descs, ondate) " + "VALUES (?, ?, ?, ?, ?, ?, ?, CURRENT_DATE())"; try (PreparedStatement stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) { stmt.setInt(1, categoryInt); stmt.setString(2, title.trim()); stmt.setString(3, tag != null ? tag.trim() : ""); stmt.setString(4, finalPhoto != null ? finalPhoto : ""); stmt.setDouble(5, priceDbl); stmt.setInt(6, stockInt); stmt.setString(7, descs.trim()); int affectedRows = stmt.executeUpdate(); if (affectedRows > 0) { response.sendRedirect("admin.jsp?currentTab=" + currentTab); return; } else { message = "添加宠物失败,请重试"; messageType = "error"; } } } else if ("edit".equals(action) && petId != null) { // 更新宠物 String sql = "UPDATE pets SET category = ?, title = ?, tag = ?, " + "photo = ?, price = ?, stock = ?, descs = ? WHERE id = ?"; try (PreparedStatement stmt = conn.prepareStatement(sql)) { stmt.setInt(1, categoryInt); stmt.setString(2, title.trim()); stmt.setString(3, tag != null ? tag.trim() : ""); stmt.setString(4, finalPhoto != null ? finalPhoto : ""); stmt.setDouble(5, priceDbl); stmt.setInt(6, stockInt); stmt.setString(7, descs.trim()); stmt.setInt(8, Integer.parseInt(petId)); int affectedRows = stmt.executeUpdate(); if (affectedRows > 0) { response.sendRedirect("admin.jsp?currentTab=" + currentTab); return; } else { message = "未找到要更新的宠物或数据未更改"; messageType = "error"; } } } } catch (SQLException e) { message = "数据库操作失败: " + e.getMessage(); messageType = "error"; e.printStackTrace(); } catch (Exception e) { message = "操作失败: " + e.getMessage(); messageType = "error"; e.printStackTrace(); } } } %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title><%= "add".equals(action) ? "添加宠物" : "编辑宠物" %> - 管理员中心</title> <style> body { font-family: Arial, sans-serif; margin: 0; padding: 20px; background-color: #f5f5f5; } .container { max-width: 800px; margin: 0 auto; background-color: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); } h1 { color: #006D77; border-bottom: 2px solid #D4B483; padding-bottom: 10px; } .form-group { margin-bottom: 20px; } label { display: block; margin-bottom: 5px; font-weight: bold; color: #006D77; } input[type="text"], input[type="number"], select, textarea { width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; box-sizing: border-box; font-size: 16px; } textarea { height: 150px; resize: vertical; } .btn-group { display: flex; gap: 10px; margin-top: 20px; } .btn { padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 16px; font-weight: bold; } .btn-primary { background-color: #006D77; color: white; } .btn-secondary { background-color: #6c757d; color: white; } .message { padding: 10px; margin-bottom: 20px; border-radius: 4px; } .required:after { content: " *"; color: red; } </style> </head> <body> <div class="container"> <h1><%= "add".equals(action) ? "添加新宠物" : "编辑宠物信息" %></h1> <% if (message != null) { %> <div class="message <%= messageType %>"><%= message %></div> <% } %> <form method="POST" action="adminpet.jsp?action=<%= action %>&currentTab=<%= currentTab %>" enctype="multipart/form-data"> <% if ("edit".equals(action)) { %> <input type="hidden" name="pet-id" value="<%= petId %>"> <% } %> <div class="form-group"> <label for="pet-name" class="required">宠物名称</label> <input type="text" id="pet-name" name="pet-name" value="<%= title != null ? title : (request.getParameter("pet-name") != null ? request.getParameter("pet-name") : "") %>" required> </div> <div class="form-group"> <label for="pet-category" class="required">分类</label> <select id="pet-category" name="pet-category" required> <option value="">-- 请选择分类 --</option> <% try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM category ORDER BY id")) { while (rs.next()) { int catId = rs.getInt("id"); String catName = rs.getString("name"); String petCategoryParam = request.getParameter("pet-category"); boolean selected = (category != null && catId == category) || (petCategoryParam != null && !petCategoryParam.isEmpty() && catId == Integer.parseInt(petCategoryParam)); %> <option value="<%= catId %>" <%= selected ? "selected" : "" %>> <%= catName %> </option> <% } } catch (SQLException e) { e.printStackTrace(); } %> </select> </div> <div class="form-group"> <label for="pet-price" class="required">价格</label> <input type="number" id="pet-price" name="pet-price" min="0.01" step="0.01" value="<%= price != null ? price : (request.getParameter("pet-price") != null ? request.getParameter("pet-price") : "") %>" required> </div> <div class="form-group"> <label for="pet-stock" class="required">库存数量</label> <input type="number" id="pet-stock" name="pet-stock" min="0" value="<%= stock != null ? stock : (request.getParameter("pet-stock") != null ? request.getParameter("pet-stock") : "") %>" required> </div> <div class="form-group"> <label for="pet-tags">特点</label> <input type="text" id="pet-tags" name="pet-tags" value="<%= tag != null ? tag : (request.getParameter("pet-tags") != null ? request.getParameter("pet-tags") : "") %>" placeholder="用逗号分隔多个标签"> </div> <div class="form-group"> <label for="pet-photo-file">宠物图片</label> <input type="file" id="pet-photo-file" name="pet-photo-file" accept="image/*"> <% if (photo != null && !photo.isEmpty()) { %> <div style="margin-top: 10px;"> <img src="<%= photo %>" alt="当前宠物图片" style="max-width: 200px; max-height: 200px;"> <input type="hidden" name="existing-photo" value="<%= photo %>"> </div> <% } %> </div> <div class="form-group"> <label for="pet-description" class="required">宠物描述</label> <textarea id="pet-description" name="pet-description" required><%= descs != null ? descs : (request.getParameter("pet-description") != null ? request.getParameter("pet-description") : "") %></textarea> </div> <div class="btn-group"> <button type="submit" class="btn btn-primary">保存</button> <button type="button" class="btn btn-secondary" onclick="location.href='admin.jsp?currentTab=<%= currentTab %>'">取消</button> </div> </form> </div> </body> </html>
06-23
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值