同一表單上傳文件並提交表單值

  • 上傳圖片和文件form的屬性應該是enctype="multipart/form-data",字符將轉成二進制流,因此request.getParameter(“user_type”)是得不到值。
  • 默認情況,傳遞參數編碼格式是application/x-www-form-urlencoded,不能用於文件上傳。

本文主要介紹表單中上傳文件並提交表單值,採用apache的commmon-upload jar包。也可以參考我的博客中另一種實現方式
【同一表單上傳頭像並提交文本值】

一、準備:

  • commons-fileupload-1.3.jar
  • commons-logging-1.1.1.jar
  • commons-io-2.2.jar
  • commons-lang3-3.2.jar

二、代碼:

2.1 html

<%@ page contentType="textml;charset=utf-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="UploadServlet" method="post" enctype="multipart/form-data">
        <input type="text" name="intro">
        <input type="file" name="f1">
        <input type="submit" value="上傳">
    </form>
</body>
<html>

2.2 servlet

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } // 解析request請求
        Iterator iter = items.iterator();
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {  // 如果是表單域 ,就是非文件上傳元素
                String name = item.getFieldName(); // 獲取name屬性的值
                String value = item.getString(); // 獲取value屬性的值
                if (item.getFieldName().equals("intro")) {
                    System.out.println(value);
                }
            } else {
                String fieldName = item.getFieldName(); // 文件域中name屬性的值
                String fileName = item.getName(); // 文件的全路徑,絕對路徑名加文件名
                String contentType = item.getContentType(); // 文件的類型
                long size = item.getSize(); // 文件的大小,以字節爲單位
                File saveFile = new File("D:/test.jpg"); // 定義一個file指向一個具體的文件
                try {
                    item.write(saveFile);// 把上傳的內容寫到一個文件中
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }


END
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章