文件上传与下载
一、使用smartupload.jar实现文件上传
//1.将jar包添加到项目中:smartupload.jar
//2.准备上传的页面
<form action="dload" method="post" enctype="multipart/form-data" >
书名:<input type="text" name="bookname"> <br>
图片:<input type="file" name="nice"><br>
<input type="submit" value="提交">
</form>
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
SmartUpload su = new SmartUpload();
JspFactory factory = JspFactory.getDefaultFactory();
PageContext pageContext = factory.getPageContext(this, req, resp, null, false, 1024, true);
su.initialize(pageContext);
su.setCharset("utf-8");
su.upload();
File file = su.getFiles().getFile(0);
String fileName = file.getFileName();
System.out.println(fileName);
String type = file.getContentType();
System.out.println("type="+type);
String url = "/uploadfiles/"+fileName;
file.saveAs(url,SmartUpload.SAVE_VIRTUAL);
req.setAttribute("filename",fileName);
String bookname = su.getRequest().getParameter("bookname");
System.out.println("bookname="+bookname);
req.getRequestDispatcher("successful.jsp").forward(req,resp);
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
//跳转到的成功界面
<h1> 上传成功</h1>
<%--展示一下图片--%>
<img src="uploadfiles/${filename}">
<%--下载图片--%>
<a href="downimg?filename=${filename}"> 下载图片</a>
二、文件的下载
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String filename = req.getParameter("filename");
String path = "/uploadfiles/"+filename;
resp.setContentType("application/octet-stream");
filename=URLEncoder.encode(filename,"utf-8");
resp.addHeader("Content-Disposition","attachment;filename="+filename );
req.getRequestDispatcher(path).forward(req,resp);
resp.flushBuffer();
}
三、注意
1、要提前在web下创建好文件夹,并且文件夹中先随便放一个文件如 a.txt 不然会找不到这个文件夹位置
2、在上传中,此时如果表单中有其他数据时,不能通过request直接获取,需要通过SmartUpload对象获取
String name=su.getRequest().getParameter("bookName");