手记

Java文件的上传与下载(Servlet+JSP)

一、文件上传
jar包:commons-fileupload-1.3.3.jar,commons-io-2.5.jar
简说流程:request<file>-->Servlet.service(转化request携带的数据,获取输入流)-->通过输出流写到服务器磁盘
1、upload.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>文件上传</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/uploadServlet" method="post" enctype="multipart/form-data">

上传文件1:<input type="file" name="file_1" size="40">
上传文件2:<input type="file" name="file_2" size="40">
<input type="submit" value="提交">

</form>

</body>
</html>
2、UploadServlet.java
public class UploadServlet extends HttpServlet
{

/**
 * 注释内容
 */
private static final long serialVersionUID = -3592230091955074245L;

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException
{
    System.out.println("i'm in uploadServlet service method");
    String resultMsg="";
   //获取真实保存的路径
    String savePath=req.getServletContext().getRealPath("/WEB-INF/upload");
    System.out.println("文件保存的路劲:"+savePath);
    File file = new File(savePath);
   //这个路径是否是个文件夹
    if(file.isDirectory() || !file.exists())
    {
        file.mkdir();
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();
   //设置默认缓存大小
    factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setHeaderEncoding("UTF-8");
   //设置文件大小限制
    upload.setFileSizeMax(40*1024*1024);
   //这里很重要  是这个数据格式的支持多媒体multipart/form-data 在JSP上传页面中也要写上
    if(!ServletFileUpload.isMultipartContent(req))
    {
       //按照传统方式获取数据
        System.out.println("数据格式不正确");
       return;
    }

    try
    {
        List<FileItem> list = upload.parseRequest(req);
        for(FileItem item : list)
        {
          //从request总获取数据,有可能是表单提交的文本键值
            if(!item.isFormField())
            {
                System.out.println("处理上传文件中");
                String filename = item.getName();
               //判断上传路径是否合法
                if(filename==null || filename.trim().equals(""))
                {
                    continue;
                }
               //获取上传文件名
                filename = filename.substring(filename.lastIndexOf("\\")+1);
                InputStream in = item.getInputStream();
                FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
                byte buffer[] = new byte[1024];
                int len = -1;
                while((len=in.read(buffer))>0)
                {
                    out.write(buffer, 0, len);
                }
                in.close();
                out.close();
                item.delete();
            }
        }
        resultMsg="上传文件成功";
    }
    catch (FileUploadException e)
    {
        resultMsg="上传失败";
        e.printStackTrace();
    }
    req.setAttribute("resultMsg", resultMsg);
    req.getRequestDispatcher("/upload_result.jsp").forward(req, resp);
}

}

0人推荐
随时随地看视频
慕课网APP

热门评论

楼主能把代码发给我学习下吗?

主要是参考他的博客:

http://www.cnblogs.com/xdp-gacl/p/4200090.html

4、download_result.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<title>资源告警</title>

</head>

<body>

${resultMsg }

</body>

</html>

查看全部评论