文件的上传与下载
文件上传的原理分析
文件拿上传的前提:
提供form表单,method必须是post
form 表单的enctype 必须是 multipart/form-data
提供input type="file"类的上传输入域
enctype 属性
作用:告知服务器请求正文的MIME类型。(请求消息头:Content-Type 作用是一致的)
可选值
application/x-www-form-urlencoded(默认):
会将请求体内容拼接成字符串发送到服务器
服务器获取数据:String name =request.getParameter("name");
multipart/form-data:
会将请求体内容转换成字节流发送到服务器(getParamter 获取不到请求数据,因为客户端发送的是字节流)
// multipart/form-data:方式提交读取流中的信息
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream inputStream = request.getInputStream();
int length = 0;
byte[] buff = new byte[1024];
while ((length = inputStream.read(buff)) != -1) {
String string = new String(buff, 0, length, "GBK");
System.out.println(string);
}
inputStream.close();
}
缺点:需要解析请求正文中的每部分内容
借助第三方的上传组件实现文件的上传
fileupload概述
fileupload 是由 apache 的commons组件提供的上传组件。它最主要的工作就是帮我们解析request.getInputStream()。
fileupload 的核心类有:
DiskFileItemFactory、ServletFileUpload、FileItem