文件上传与下载

来源:互联网 发布:黑客破解刷扣币软件 编辑:程序博客网 时间:2024/05/23 01:26

上传

第一步导包

l commons-fileupload.jar,核心包;

l commons-io.jar,依赖包。

第二步:

完成index.jsp,只需要一个表单。注意表单必须是post的,而且enctype必须是mulitpart/form-data的。

    <form action="${pageContext.request.contextPath }/FileUploadServlet" method="post" enctype="multipart/form-data">

    用户名:<input type="text" name="username"/><br/>

    文件1<input type="file" name="file1"/><br/>

    <input type="submit" value="提交"/>

    </form>

 

第三步:

完成FileUploadServlet

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 因为要使用response打印,所以设置其编码

response.setContentType("text/html;charset=utf-8");

// 创建工厂

DiskFileItemFactory dfif = new DiskFileItemFactory();

// 使用工厂创建解析器对象

ServletFileUpload fileUpload = new ServletFileUpload(dfif);

try {

// 使用解析器对象解析request,得到FileItem列表

List<FileItem> list = fileUpload.parseRequest(request);

// 遍历所有表单项

for(FileItem fileItem : list) {

// 如果当前表单项为普通表单项

if(fileItem.isFormField()) {

// 获取当前表单项的字段名称

String fieldName = fileItem.getFieldName();

// 如果当前表单项的字段名为username

if(fieldName.equals("username")) {

// 打印当前表单项的内容,即用户在username表单项中输入的内容

response.getWriter().print("用户名:" + fileItem.getString() + "<br/>");

}

else {//如果当前表单项不是普通表单项,说明就是文件字段

String name = fileItem.getName();//获取上传文件的名称

// 如果上传的文件名称为空,即没有指定上传文件

if(name == null || name.isEmpty()) {

continue;

}

// 获取真实路径,对应${项目目录}/uploads,当然,这个目录必须存在

String savepath = this.getServletContext().getRealPath("/uploads");

// 通过uploads目录和文件名称来创建File对象

File file = new File(savepath, name);

// 把上传文件保存到指定位置

fileItem.write(file);

// 打印上传文件的名称

response.getWriter().print("上传文件名:" + name + "<br/>");

// 打印上传文件的大小

response.getWriter().print("上传文件大小:" + fileItem.getSize() + "<br/>");

// 打印上传文件的类型

response.getWriter().print("上传文件类型:" + fileItem.getContentType() + "<br/>");

}

}

catch (Exception e) {

throw new ServletException(e);

}

下载

download.jsp

    <a href="<c:url value='/DownloadServlet?path=这个杀手不太冷.avi'/>">这个杀手不太冷.avi</a><br/>

    <a href="<c:url value='/DownloadServlet?path=白冰.jpg'/>">白冰.jpg</a><br/>

    <a href="<c:url value='/DownloadServlet?path=说明文档.txt'/>">说明文档.txt</a><br/>

 

DownloadServlet.java

String filename = request.getParameter("path");

// GET请求中,参数中包含中文需要自己动手来转换。

// 当然如果你使用了全局编码过滤器,那么这里就不用处理了

filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");

String filepath = this.getServletContext().getRealPath("/WEB-INF/uploads/" + filename);

File file = new File(filepath);

if(!file.exists()) {

response.getWriter().print("您要下载的文件不存在!");

return;

}

// 所有浏览器都会使用本地编码,即中文操作系统使用GBK

// 浏览器收到这个文件名后,会使用iso-8859-1来解码

filename new String(filename.getBytes("GBK"), "ISO-8859-1");

response.addHeader("content-disposition""attachment;filename=" + filename);

IOUtils.copy(new FileInputStream(file), response.getOutputStream());

ssh框架


0 0