JavaWeb实现文件上传下载

发布时间 2023-11-27 15:29:04作者: Xproer-松鼠

JavaWeb中实现文件上传下载
使用jar包:smartupload.jar,该包封装了IO流的操作,如果使用Java自带的IO操作会比较繁琐

文件上传的基本步骤
@WebServlet(urlPatterns = "/uploads",name = "UploadServlet")
//创建文件上传对象
SmartUpload smartupload = new SmartUpload();
//初始化上传操作
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this,req,resp,null,false,1024,true);
smartupload.initialize(pageContext);
//也可使用以下方法初始化
//smartupload.initialize(this.getServletConfig(),request,response);
//设置编码
smartupload.setCharset('utf-8');
//上传准备
smartupload.upload()
//保存到指定文件夹下
smartupload.saveAs("/imgs");

//获取文件信息 1、通过传入下标的方式获取文件 2、获取文件名 3、获取文件类型 4.获取文件扩展名
File file = smartUpload.getFiles().getFile(0)
String name = file.getFileName();
String contentType = file.getContentType();
String ext = file.getFileExt()

//通过该种方式上传可以指定文件的名称 获取客户端的IP地址,以该IP作为文件名称
String uploadPath = "/uploadfiles/"+request.getRemoteAddr()+ext;
//保存到指定路径 第二个参数表示当前的文件要传入到虚拟路径上
file.saveAs(uploadPath,File.SAVES_VIRTUAL);


Q:pageContext对象是jsp的内置对象,那么在Servlet中该怎么获取呢?
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this,req,resp,null,false,1024,true)
/* 参数讲解
this -- 代表servlet对象
null -- 该处需要传入字符串,代表页面错误时需要跳转的页面
false -- 该处代表是否需要使用session,需要则填true
1024 -- 该处代表设置的缓冲区的大小,缓冲区是个字节数组,所以是字节为单位
true -- 代表当缓冲区满的时候溢出时自动刷新到输出流还是抛出IOException异常。true为自动刷新
*/

smartupload常用方法
//将全部文件保存到指定目录下,并返回保存的文件个数
public int save(String pathName)
//指定允许上传的文件扩展名,接受一个扩展名列表,逗号分隔
public void setAllowFilesList(String fileList)
//指定了禁止上传的文件扩展名列列表,每个扩展名间以逗号分隔
public void setDeniedFilesList(String fileList)
//设定每个文件允许上传的最大长度
public void setMaxFileSize(long filesize)
//设定允许上传文件的总长度
public void setTotalMaxFileSize(long totalfilesize)

Jsp上传页面的代码如下:
<!-- 注:(1)form标签中要添加enctype属性 (2)提交方式必须是post,否则报错 -->
<form action="smartupload.jsp" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="uname"><br/>
照片:<input type="file" name="pic"><br/>
<input type="submit" value="上传">
</form>

Q:表单使用**enctype=“multipart/form-data”**进行了二进制的封装,无法使用request.getParameter()方法获取值了,而是二进制的byte流了,那么如何获取表单内uname属性的值呢?

A:这个时候如果想要获取表单中的请求值,只有使用SmartUpload中的方法getRequest.getParameter()方法进行获取。即使用SmartUpload中封装好的Request对象获取请求参数

//注意:必须放在上传准备smartupload.upload()的后面
//解决乱码 new String(uname.getBytes("GBK"),"utf-8")
String uname = smartupload.getRequest.getParameter("name");

文件下载基本步骤
@WebServlet(urlPatterns = "/downimg",name = "DownServlet")
//获取需要下载的文件名称 然后去对应的存放文件的路径中寻找
String filename = request.getParameter("filename");
String path = "/imgs/"+filename;
//设置响应类型,表示返回的的是流
response.setContentType("application/octet-stream");
//添加头信息 使用URLEncoder内的方法指定编码,防止文件名乱码
response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
//跳转页面
request.getRequestDispatcher(path).forward(request,response);
//清空缓存区
response.flushBuffer();

Jsp下载页面代码
<a href="${pageContext.request.contextPath}/downimg?filename=like.png">下载</a>

参考文章:http://blog.ncmem.com/wordpress/2023/11/27/javaweb%e5%ae%9e%e7%8e%b0%e6%96%87%e4%bb%b6%e4%b8%8a%e4%bc%a0%e4%b8%8b%e8%bd%bd/

欢迎入群一起讨论