文件上传与下载
- 文件上传:是只把本地文件以流的方式提交到服务器上,服务器读取该文件流,并写入到服务器的磁盘上。
- 文件在线查看:是指把服务器上的文件以流的方式读取,并写入到本地内存。
- 文件下载:是指把服务器上的文件以流的方式读取并写入本地磁盘。
- 字节流、文件流、method必须是post
1.1 上传的基本原理
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>测试文件上传</title>
<base href="${pageContext.request.contextPath}/"/>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="name" ><br>
密码:<input type="password" name="pwd"><br>
文件:<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
<a href="download?name=0feed66f09c1405b807a4eb28b50d89d"> 查看图片</a>
</body>
</html>
如果不设置enctype="multipart/form-data"的话,表单默认以application/x-www-form-urlencoded格式进行提交,提交后后台接收的数据为:username=zhangsan&age=20&photo=1.txt,此时servlet会进行字符串切割,使用request.getParamater就可以得到不同的name对应的值。此时文件流根本没有上传,无法得到文件上传的效果。虽然表单名是file但是得到的是file那个文件字符串的名字。
要想实现文件上传需要把表单的提交格式改成:enctype=“multipart/form-data”,此时会把所有的数据提交到流中。代码如下:
ServletInputStream is = request.getInputStream();
FileOutputStream fos=new FileOutputStream(new File("E:\\picture\\2.txt"));
byte[] buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
fos.write(buffer,0,len);
}
fos.flush();
fos.close();
此时的表单其他数据都为null,文件名字也为空,而写入到本地磁盘上的文件格式为:
------WebKitFormBoundary7fU67Im8KiBN8Zfm
Content-Disposition: form-data; name="username"
zhangsan
------WebKitFormBoundary7fU67Im8KiBN8Zfm
Content-Disposition: form-data; name="age"
20
------WebKitFormBoundary7fU67Im8KiBN8Zfm
Content-Disposition: form-data; name="photo"; filename="1.txt"
Content-Type: text/plain
AAAAA
BBBBB
CCCCC
DDDDD
------WebKitFormBoundary7fU67Im8KiBN8Zfm--
此时需要字符串切割,并分析字符串才能得到文本内容。在Servlet3.0以前的版本,Servlet本身没有提供此功能,需要结合第三方文件库才可以使用文件上传解析,手动解析代码比较复杂。
在Servlet3.0以后的版本,在Servlet中可以使用@MultipartConfig注解来实现文件上传的解析。用request.getpart()来处理文件内容。
为了让上传的文件名称不重复,可以用UUID来生成唯一的字符串。例如:
String s = UUID.randomUUID().toString().replace("-", "");
System.out.println(s);
1.2文件的上传和下载
文件查看即将服务器上的文件以InputStream的方式打开,并写入到response的outputStream中。
文件下载只需要将response的header设置为下载即可。
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name");
InputStream is = new FileInputStream(new File("e:/picture/" + name));
ServletOutputStream fos = response.getOutputStream();
response.setHeader("content-disposition","attachment;filename="+name+"_13");
//服务器响应给客户端响应流
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
fos.flush();
fos.close();
}
resp.setHeader(“content-disposition”, “attachment;filename=2.png”);
如果需要把文件原始名称拼接到服务器保存的文件路径中,为了避免特殊符号,需要对URL中的字符进行编解码。例如:
String s = "中国/1.jpg";
// 在URL中字符编码
String encode = URLEncoder.encode(s, "utf-8");
System.out.println(encode);
// 在URL中字符解码
String decode = URLDecoder.decode(encode, "utf-8");
System.out.println(decode);