iT邦幫忙

0

【左京淳的JAVA WEB學習筆記】第六章 檔案上傳

  • 分享至 

  • xImage
  •  

檔案上傳與一般表單提交的格式不同。
一般表單提交默認enctype = "application/x-www-form-urlencoded"
檔案上傳則必須設置enctype = "multipart/form-data"

動手做做看
在main資料夾下,新建一個文件上傳頁面uploadFile.jsp

<%
  String path = request.getContextPath();
  String basePath = request.getScheme() + "://" + request.getServerName()  
  + ":" + request.getServerPort() + path + "/";
%>
<body>
  <h1>文件上傳</h1>
  <form action="<%=basePath%>FileSvl" enctype = "multipart/form-data" method = "post">
    文件名:<input type="text" name="fname" id="fname">
    <input type="file" name="file" onchange="show(this)"><br>
  <input type="submit" value="上傳">
  ${msg}
  </form>
</body>
<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.4.4.min.js"></script>
<script type="text/javascript">
  function show(source){
    var arrs = $(source).val().splite('\\');
    var filename = arrs[arrs.length - 1];
    $(#fname).val(filename);
  }
</script>

註:js腳本用來顯示被選擇的文件名稱。

新建一個FileSvl

import javax.servlet.http.Part;

@WebServlet("/FileSvl")
@MultipartConfig(maxFileSize = 300 * 1024)
public class FileSvl extends HttpServlet {
  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.getRequestDispatcher("/main/uploadFile.jsp").forward(request, response);
  }

  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String fname = request.getParameter("fname");
    try {
      Part part = request.getPart("file");
      String picPath = request.getServletContext().getRealPath("/") + "pic";
      part.write(picPath + "/" + fname);
      request.setAttribute("msg","上傳成功");
    }catch(Exception e) {
      e.printStackTrace();
      request.setAttribute("msg", e.getMessage());
    }
    request.getRequestDispatcher("/main/uploadFile.jsp").forward(request, response);
  }
}

註:用@MultipartConfig標籤可限制上傳檔案大小
使用request.getPart()取得上傳檔案後儲存在變數裡,再轉存到指定路徑的資料夾內。


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言