jsp的文件上传

在web端,想用jsp写个文件上传,发现如何只用普通的<input type=”file” ·····>来的写话是不能把文件和表单其他内容一起上传。

 

于是尝试用了SmartUpload,发现SmartUpload对表单的中文能里处理会有乱码,即使用了

new String(mySmartUpload.getRequest().getParameter("news_type").trim().getBytes(),"utf-8");

的话,接收表单内容是即使显示中文,但也极其不稳定,有些字是中文,有些字是乱码。

 

最后改用了commons—fileuoload框架。能顺利解决中文乱码问题。代码如下:

 

 

protectedvoid doPost(HttpServletRequest request,HttpServletResponse response) throwsServletException, IOException {

 

    response.setContentType("text/html;chaeset=utf-8");

    request.setCharacterEncoding("utf-8");

    response.setCharacterEncoding("utf-8");

    PrintWriter out = response.getWriter();

     boolean isMultipart = ServletFileUpload.isMultipartContent(request);//检查输入请求是否为multipart表单数据。

        if (isMultipart == true) {

          FileItemFactory factory = new DiskFileItemFactory();//为该请求创建一个DiskFileItemFactory对象,通过它来解析请求。执行解析后,所有的表单项目都保存在一个List中。

       

          ServletFileUpload upload = new ServletFileUpload(factory);

          List<FileItem> items = null;

        try {

            items =upload.parseRequest(request);

        } catch (FileUploadException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

          Iterator<FileItem> itr = items.iterator();

          while (itr.hasNext()) {

              FileItem item = (FileItem) itr.next();

              //检查当前项目是普通表单项目还是上传文件。

              if (item.isFormField()) {//如果是普通表单项目,显示表单内容。

                     String fieldName =item.getFieldName();

              if (fieldName.equals("name")) //对应demo1.htmltype="text" name="name"

               

                     out.print("the field name is  " + item.getString("utf-8"));//显示表单内容。

                     out.print("<br>");

              } else {//如果是上传文件,显示文件名。

                  String fileName=item.getName();

                  String path="F:/img";

                   File fullFile=new File(item.getName());

                      File savedFile=new File(path,fullFile.getName());

                      try {

                        item.write(savedFile);

                    } catch (Exception e) {

                        // TODO Auto-generated catch block

                        e.printStackTrace();

                    }

                     out.print("the upload file name is  " + item.getName());

                     out.print("<br>");

              }

          }

        } else {

          out.print("theenctype must be multipart/form-data");

        }

 

    }

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值