工具
smartupload.jar
使用
页面部分
- 必须使用POST提价
- 表单属性必须有
enctype="multipart/form-data"
<form action="toUpload" method="post" enctype="multipart/form-data" >
书名:<input type="text" name="bookName"/><br>
图片:<input type="file" name="自定义名称"/><br>
<input type="submit" value="提交"/>
</form>
文件上传
public void upload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//上传文件
SmartUpload su=new SmartUpload();
//获得pageContext对象
JspFactory factory=JspFactory.getDefaultFactory();
PageContext pagecontext=factory.getPageContext(this, request,response, null,false,1024,true);
su.initialize(pagecontext);
su.setCharset("utf-8");
//实现文件数据的上传
su.upload();
File file = su.getFiles().getFile(0);
//得到文件的基本信息
String filename=file.getFileName();
String type=file.getContentType();
String url="uploadfile/"+filename;
//将上传文件保存到指定目录
file.saveAs(url, SmartUpload.SAVE_VIRTUAL);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
文件下载
String name=request.getParameter("filename");
String url="uploadfile/"+name;
//将响应的内容设置为通用的二进制流
response.setContentType("application/octet-stream");
//attachment 告诉浏览器以附件的方式下载文件(弹出下载框)
name=URLEncoder.encode(name,"utf-8");
response.addHeader("Content-Disposition","attachment;filename="+name); request.getRequestDispatcher(url).forward(request, response);
//清空缓冲区:将服务端缓冲区的文件内容,立即权并不传送给客户端
response.flushBuffer();