web如何上传文件以及在enctype="multipart/form-data"情况下如何获取除文件外的数据

最近学校的作业遇到这样的问题,web如何上传文件和获取除文件外其他数据,在获取其他文本数据时为null或乱码的问题,解决之后不妨记下来,供大家参考
首先请看jsp代码
<body>
	<form action="UploadServlet" method="post" enctype="multipart/form-data">
		<input type="file" name="uploadFile" />
		<input type="submit" />
	</form>
</body>
	
如何获取第一个文件项
首先需要在webContent下的lib中引用三个工具包

web如何上传文件以及在enctype=
下面是java代码

package com.crx.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

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

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class UploadServlet
 */
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//1.磁盘文件项工厂
		DiskFileItemFactory factory = new DiskFileItemFactory();
		//2.服务应用文件上传(工具)
		ServletFileUpload upload = new ServletFileUpload(factory);
		//3.获取数据
		try {
			FileItemIterator iter = upload.getItemIterator(request);
			//4.获取迭代器中第一个数据信息
			FileItemStream stream = iter.next();
			//5.通过打开流方式获取出输入流
			InputStream input = stream.openStream();
			//6.输出流
			//6.1 获取本地服务器的地址(浏览器之间不兼容的问题)
			String tomcatPath = request.getSession().getServletContext().getRealPath("/img");
			System.out.println(tomcatPath);
			//6.2 给上传图片重命名(不能有重名的文件)
			String new_fileName = "img_" + new Date().getTime() + stream.getName().substring(stream.getName().lastIndexOf("."));
			FileOutputStream output = new FileOutputStream(tomcatPath + "/" + new_fileName);
			
			//7.创建一个字节数组
			byte[] buffer = new byte[1024];
			int len = 0;
			while((len = input.read(buffer)) > 0) {
				output.write(buffer, 0, len);
			}
			//8.关闭流
			output.close();
			input.close();
			
			request.setAttribute("imgName", new_fileName);
			request.getRequestDispatcher("showImg.jsp").forward(request, response);
			
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

在webContent创建一个文件夹存放文件(代码中以图片为例)
这样就获取了第一个文件项,如何获取下面的飞文件项呢,请看以下代码

//第二个控件的信息(是以流的形式传递过来的)
			FileItemStream stream1 = iter.next();
			while(iter.hasNext()){
				FileItemStream stream2 = iter.next();
				if (stream2.getName() == null) {
					BufferedReader reader = new BufferedReader(new InputStreamReader(stream1.openStream()));
					String text = reader.readLine();
					System.out.println("读取到的文本是:"+text);
				} else {
					System.out.println("读取完毕");
				}
			}

你可能感兴趣的:(servlet,javascript)