<1>获取二进制文件流并输出
InputStream inputStream = request.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String s;
while ((s = reader.readLine()) != null) {
System.out.println(s);
}
<2>借用服务器提供的架包(commons-fileupload, commons-io)
package servlet_file_upload;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
@WebServlet("/FileUploadServlet")
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileUploadServlet() {
super();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 设置跨域访问
response.addHeader("Access-Control-Allow-Origin", "*");
// 设置请求和返回编码为 UTF-8, 如非必要,不要设置,不然会影响文件扩展名的获取
//response.setCharacterEncoding("UTF-8");
//request.setCharacterEncoding("UTF-8");
// 获取项目根目录绝对路径
String path = getServletContext().getRealPath("");
// 设置存放返回路径的变量
StringBuilder returnPath = new StringBuilder(200);
try {
// 实例化本地磁盘工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置文件上传启用的缓存的值,每 2M 写入一次临时文件
factory.setSizeThreshold(2 * 1024 * 1024);
// 设置缓存文件的临时存放目录
factory.setRepository(new File(path + "Upload"));
// 实例化文件上传类
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置全部文件上传的最大值
//upload.setSizeMax(Integer.valueOf(100) * 1024 * 1024);
// 获取前端上传的文件列表
List<FileItem> items = upload.parseRequest(request);
// 循环所有上传的字段或文字
for (FileItem item : items) {
if (item.isFormField()) {
// 获取字段名
String name = item.getFieldName();
// 获取字段值 括号内的参数不可少否则乱码
String value = item.getString("UTF-8");
// 打印不是文件的字段
System.out.println(name + ".." + value);
} else {
// 获取文件名
String name = item.getName();
// 确定文件存放的相对路径
String filePath = "Upload/" + System.currentTimeMillis() + "." + name.split("\\.")[1];
// 将文件写入指定的路径
item.write(new File(path + filePath));
// 删除缓存文件, 如果没有设置, 大部分时候临时文件也会被删除
item.delete();
// 将相对路径赋值给返回值
returnPath.append(filePath);
// 路径之间用逗号隔开
returnPath.append(",");
}
}
response.getWriter().write(returnPath.substring(0, returnPath.length()- 1));
} catch (Exception e) {
response.getWriter().write("上传失败");
}
}
}
注: 前端代码请参考 http://www.cnblogs.com/lovling/p/6685634.html