上传文件之处理非File字段

参考how2j.cn  这个网站很不错。

附上链接,网站有源码,可以自己试试

http://how2j.cn/k/servlet/servlet-upload/587.html#nowhere

<form action="uploadPhoto" method="post" enctype="multipart/form-data">
名称:<input type="text" name="Name" /> <br>
头像 : <input type="file" name="filepath" /> <br>
  <input type="submit" value="上传">
</form>

因为浏览器指定了以二进制的形式提交数据,那么就不能通过常规的手段获取非File字段:

request.getParameter("Name")

在遍历Item时(Item即对应浏览器提交的字段),可以通过  item.isFormField  

来判断是否是常规字段还是提交的文件。 当item.isFormField返回true的时候,就表示是常规字段。

然后通过item.getFieldName()和item.getString()就知道分别是哪个字段,以及字段的值了。

 public void doPost(HttpServletRequest request, HttpServletResponse response) {

  

        String filename = null;

        try {

            DiskFileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload upload = new ServletFileUpload(factory);

            // 设置上传文件的大小限制为1M

            factory.setSizeThreshold(1024 1024);

             

            List items = null;

            try {

                items = upload.parseRequest(request);

            catch (FileUploadException e) {

                e.printStackTrace();

            }

  

            Iterator iter = items.iterator();

            while (iter.hasNext()) {

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

                if (!item.isFormField()) {

  

                    // 根据时间戳创建头像文件

                    filename = System.currentTimeMillis() + ".jpg";

                    String photoFolder = "e:\\project\\j2ee\\web\\uploaded";

                    File f = new File(photoFolder, filename);

                    f.getParentFile().mkdirs();

  

                    // 通过item.getInputStream()获取浏览器上传的文件的输入流

                    InputStream is = item.getInputStream();

  

                    // 复制文件

                    FileOutputStream fos = new FileOutputStream(f);

                    byte b[] = new byte[1024 1024];

                    int length = 0;

                    while (-1 != (length = is.read(b))) {

                        fos.write(b, 0, length);

                    }

                    fos.close();

  

                else {

                    System.out.println(item.getFieldName());

                    String value = item.getString();

                    value = new String(value.getBytes("ISO-8859-1"), "UTF-8");

                    System.out.println(value);

                }

            }

             

            String html = "<img width='200' height='150' src='uploaded/%s' />";

            PrintWriter pw= response.getWriter();

            pw.format(html, filename);

             

        catch (FileNotFoundException e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

猜你喜欢

转载自blog.csdn.net/qq_41566772/article/details/81067546