Tomcat 下 JSP(enctype="multipart/form-data") post 提交时中文乱码解决方案

This problem had been bugging me for 3 days!

Background:

Use JSP and Servlet to implement file upload。The uploaded file is stored in file system, the related info like description and Mime type, size and path name is stored in MySQL。JSP and DB table both use UTF-8 CHARSET. If successfully,Servelet forwards to success page with related file info returned.

Promblem(all happened with Chinese characters):

1. On Jetty,except the filename was encoded by UTF-8(unreadable), everything is good.
2. But on Tomcat, all that characters were inserted into DB and returned to client were corrupted.

Solution:
1.No matter how you set a form's charset,Tomcat always treats it by iso 8859-1.So what we read from the input strem are 8859-1 encoded.
If we need to search a substring in the content, we have to use getBytes("ISO-8859-1") on the substring. Also, use String(subBytes, "UTF-8") to return some substrings.

2.In the success jsp, we should add <%@ page contentType="text/html;charset=UTF-8"%>.

(And the <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> is useless.)

3.In the post() method of Servlet, we must add request.setCharacterEncoding("UTF-8"); And it must sit before any sentences that read input stream.

After the previous steps, everything is good on Tomcat.

But on Jetty, the filename was still encoded by UTF-8. I tried to convert UTF-8 to system default encoding by new String(fileName.getBytes("UTF-8"), system.getProperty("file.encoding")), but no use.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
解决enctype= multipart/form-data无法传递其他参数的方法有多种。 一种常见的解决方法是使用一个隐藏的表单字段将额外的参数传递到服务器端。在form标签中添加一个隐藏的input标签,将需要传递的参数作为该字段的值。在提交表单,该参数会随着文件一起被发送到服务器端。 另一种方法是使用JavaScript来动态地修改表单的action属性,并将额外的参数作为查询字符串添加到action中。当用户点击提交按钮,JavaScript会通过监听表单的提交事件,在提交之前修改action属性并将额外参数添加到其中。这样,提交表单就会将所有参数一起发送到服务器端。 如果使用的是Ajax来提交表单,可以将其他参数组成一个对象,然后使用FormData对象来存储文件和其他参数。FormData对象可以通过append()方法将文件和其他参数添加到其中,然后通过XmlHttpRequest对象将FormData对象发送到服务器端。 还有一种解决方法是使用服务器端的处理程序来解析multipart/form-data类型的请求,然后从请求体中解析出文件和其他参数。可以根据服务器端的开发语言和框架来选择合适的处理程序,例如在PHP中可以使用$_FILES数组来获取文件,使用$_POST数组来获取其他参数。 综上所述,通过隐藏字段、JavaScript、FormData对象或服务器端的处理程序,都可以实现在enctype= multipart/form-data类型的表单中传递其他参数。选择哪种方法取决于具体的需求和技术环境。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值