javaweb文件上传中文乱码

文件上传小例子:
问题:
前提:response.setContentType(“text/html;charset=UTF-8”);
request.setCharacterEncoding(“UTF-8”);
利用servletFileUpload.parseRequest(request)解析了之后,输出的普通表单项的值有中文乱码问题。
解决方法:
fileItem.getString(“UTF-8”):注意UTF-8的问题


public class UploadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");

        // 创建工厂
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        // 创建解析器
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        try {
            // 解析request,包含普通表单项和文件表单项
            List fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                // isFormField()判断是否为普通表单项
                if (fileItem.isFormField()) {
                    // getFieldName()获取表单名
                    String fieldName = fileItem.getFieldName();
                    if (fieldName.equals("username")) {
                        // 获取表单项的value,注意"UTF-8"
                        fileItem.getString("UTF-8");
                        response.getWriter().print("用户名:" + fileItem.getString("UTF-8") + "
"
); } } else { String fieldName = fileItem.getFieldName(); // 获取文件表单项的文件名getName() String fileName = fileItem.getName(); if (fileName == null || fileName.isEmpty()) { // 说明没有上传文件,处理... } String savePath = this.getServletContext().getRealPath("/WEB-INF/uploads"); File file = new File(savePath, fileName); // 上传文件到服务器 fileItem.write(file); response.getWriter().print("表单名:" + fieldName + "文件名:" + fileName + "
"
); response.getWriter().print("文件大小: " + fileItem.getSize() + "
"
); response.getWriter().print("文件类型: " + fileItem.getContentType() + "
"
); } } } catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } }

你可能感兴趣的:(javaweb)