jsp同時上傳文件和表單

附代碼示例:

要填寫的表單及文件代碼如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上傳圖片功能</title>
</head>
<body>
    <form action="a.do" method="post" enctype="multipart/form-data">
        <div align="center" >
            <label>姓名: </label>
            <input name="stuname"  type="text"/> 
            <label>學號: </label>
            <input name="stuno"  type="text"/>
            <label>年齡: </label>
            <input name="age"  type="text"/> 
            <label>電話號碼: </label>
            <input name="phone"  type="text"/>
            <br><br>
            <label>性別: </label>
            <input name="sex"  type="radio" value="男" checked/> 男
            <input name="sex"  type="radio" value="女"/> 女<br><br>
            <label>照片: </label>
            <input name="picture" value="" type="file"/>
            <br><br>
            <input value="註冊" type="submit"/> 
    	</div>
    </form>
</body>
</html>

Servlet接收參數和文件的代碼如下:

package test;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

public class A extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.sendRedirect("abc.jsp");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 初始化
		SmartUpload smartUpload = new SmartUpload();
		ServletConfig config = this.getServletConfig();
		smartUpload.initialize(config, request, response);
		try {
			// 上傳文件
			smartUpload.upload();
			// 得到上傳的文件對象
			com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);
			String name = smartFile.getFileName();
			// 保存文件
			smartFile.saveAs("/picture/"+name, SmartUpload.SAVE_AUTO);
			// 傳過來的註冊數據
			// 只需要new SmartUpload().getRequest().getParameter(""))就能獲取到相應的表單數據
			String stuname = smartUpload.getRequest().getParameter("stuname");
			int stuno = Integer.parseInt(smartUpload.getRequest().getParameter("stuno"));
			System.out.println("name:  "+stuname+"   stuno:  "+stuno);
			response.sendRedirect("abc.jsp");
		} catch (SmartUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}

注意:  1.servlet代碼去掉包名,換成自己的。

            2.需要在自己的WebContent目錄下創建picture文件。

            3.導入smartupload.jar包

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