servlet实现上传下载,首先上传下载文件都是数据在进行交互,数据交互就一定需要IO流
数据上传(图片):
原理,页面将图片以二进制(request)的形式提交上服务器,服务器获取request的输入流,读取出所有的二进制数据,转换成图片即可。
这个操作难度不大,但是过程比较复杂,所以我们一般用插件jspsmartupload
//创建上传数据对象
SmartUpload upload = new SmartUpload();
//初始化数据
upload.initialize(this.getServletConfig(), request, response);
try {
//读取数据
upload.upload();
//保存文件
//获取当前项目的真实路径
String path = request.getRealPath("/");
System.out.println(path);
upload.save(path);
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
html页面注意一个事情,就是需要吧表单的数据格式进行修改
<form enctype="multipart/form-data"
action="http://localhost:8088/TestWeb5.0.0_upload_download/DownLoadServlet"
method="post" >
<input type="file" name="img">
<input type="submit" value="上传。。。">
</form>
由于我们发现服务器上上传的图片,名字是图片的原名字,这种情况会导致图片可能会被覆盖,就是图片名字重名,所以我们需要对图片的名字进行优化。
Files files = upload.getFiles();
for(int i=0; i<files.getCount(); i++) {
File file = files.getFile(i);
String fileName = file.getFileName(); //a.png
//截取字符串
String end = fileName.substring(fileName.indexOf("."), fileName.length());
String newName = ""+System.currentTimeMillis() +
end;//23749823749237429332192.168.0.112.png
file.saveAs(path + "/" + newName);
}
注意:
此处我们这种方式是无法进行商业开发的,所以未来我们需要一个专业的图片服务器,复杂存储和访问图片,我们程序服务器知识一个中转站,通过程序吧图片中专到我们的图片,这个声请购买图片云服务器。
文件瞎子啊:
1、设置http请求头
2、读取文件
3、输出文件
String fileName = “a.txt”;
response.setHeader(“Content-Disposition”,
“attachment; filename=\”” + fileName + “\”“);
FileInputStream fis = new FileInputStream("e:/a.txt");
byte b[] = new byte[1024];
fis.read(b);
fis.close();
OutputStream out = response.getOutputStream();
out.write(b);
out.flush();
out.close();