日期:2014-05-18  浏览次数:20719 次

怎么用一个表单同时提交上传文件 和文本框的信息!(不用控件)
小弟写了个上传文件的测试...代码如下
==================
package org.upload;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;

public class Upload extends HttpServlet {

/**
* Constructor of the object.
*/
private String uploadPath = "D:\\"; // 用于存放上传文件的目录

private String tempPath = "C:\\upload\\tmp"; // 用于存放临时文件的目录

private String realBaseDir;

public Upload() {
super();
}

/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}

/**
* The doGet method of the servlet. <br>

* This method is called when a form has its tag value method equals to get.

* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

doPost(request, response);
}

/**
* The doPost method of the servlet. <br>

* This method is called when a form has its tag value method equals to
* post.

* @param request
* the request send by the client to the server
* @param response
* the response send by the server to the client
* @throws ServletException
* if an error occurred
* @throws IOException
* if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

try {
DiskFileUpload fu = new DiskFileUpload();
// 设置最大文件尺寸,这里是4MB
fu.setSizeMax(419430400);
// 设置缓冲区大小,这里是4kb
fu.setSizeThreshold(40960);
// 设置临时目录:
fu.setRepositoryPath(tempPath);

// 得到所有的文件:
List fileItems = fu.parseRequest(request);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
// 获得文件名,这个文件名包括路径:
String fileName = fi.getName();
System.out.println("jjjjj : " + fileName);
String fileName2 = fileName.substring

(fileName.lastIndexOf("\\") + 1, fileName.length());
if (fileName != null) {
// 在这里可以记录用户和文件信息
// 写入文件从fileName中提取文件名:
File toSave = new File(realBaseDir);
if (!toSave.isDirectory()) {
toSave.mkdirs();
}
fi.write(new File(realBaseDir + "//" + fileName2));
}
}
// 跳转到上传成功提示页面
} catch (Exception e) {
// 可以跳转出错页面
}
}

/**
* Initialization of the servlet. <br>