標籤:type nal github 通過 添加 coding 姓名 檔案上傳 extend
檔案上傳是開發一個網站最基本的一個需求功能
前台頁面的設定:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><form action="upload.do?method=upload" method="post" enctype="multipart/form-data"> 美照:<input type="file" name="image"/><br> 姓名:<input type="text" name="name"/><br> <input type="submit"/></form>
要點:
1、提交的方式必須是post方式,因為get方式是通過url地址欄進行資料的傳遞的,所以不能選用get方法
2、在form標籤中需要添加 enctype="multipart/form-data"屬性,如果不添加需要上傳的資訊內容不能傳遞到後台,只會傳遞該檔案的檔案名稱過去。使用了該屬性則必須在後台使用工具將資料分離
後台設定:
在src目錄下建立一個com.servlet包,然後添加一個UploadServlet.java類,並將該類註冊到web.xml中
拷貝cos.jar-->https://github.com/DarknessShadow/DataMaven 包放於web項目的lib目錄下(cos.jar主要功能是用來分離前台傳遞過去的資料,然後將分離出的檔案在寫入到指定的路徑中)
package com.servlet;import java.io.IOException;import java.util.Map;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.oreilly.servlet.MultipartRequest;import com.util.Upload;public class UploadServlet extends HttpServlet{ @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); String method = request.getParameter("method"); System.out.println(method); if("upload".equals(method)){ doUpload(request,response); } } private void doUpload(HttpServletRequest request, HttpServletResponse response) throws IOException {// 按照原先的servlet的接收方式,是接收不到資料的,必須使用工具將資料分離// String image = request.getParameter("image");// System.out.println(image);// String name = request.getParameter("name");// System.out.println(name); // 同過request對象擷取儲存圖片的真實路徑 String path = request.getServletContext().getRealPath("/images"); System.out.println(path);// 擷取儲存資料的對象,並設定其對應的編碼,路徑 MultipartRequest mr = new MultipartRequest(request, path,"utf-8");// 獲得前台發送過來的檔案原始名稱 String image = mr.getOriginalFileName("image"); System.out.println(image);// 擷取前台表單發送過來的普通資料 String name = mr.getParameter("name"); System.out.println(name); }}
缺陷:重新命名問題、中文顯示問題
檔案上傳(表單檔案上傳)