Servlet文件上传下载

文件上传

关联jar包:

commons-fileupload-1.4.jar.zip
commons-io-2.6.jar.zip
jsmartcom_zh_CN.jar

方法1--smartupload.jar

上传主要两个文件:一个是Servlet文件,还有一个是jsp文件

 以下为Servlet文件

package servlet;


import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

@WebServlet(urlPatterns = "/uploadtest")
public class UploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        try {

            //1.创建上传文件的对象
            SmartUpload smartUpload = new SmartUpload();
            //2.初始化上传操作
            //s:为响应错误页面.可以不指定
            //b:是否使用session
            //i:int 字节
            //b1:内存溢出部分是否输出到输出流:true

            PageContext pageContext = JspFactory.getDefaultFactory()
                    .getPageContext(this, req, resp, null, false, 1024, true);
            smartUpload.initialize(pageContext);
//        3.上传
            smartUpload.upload();
//        4.获取文件信息
            File file = smartUpload.getFiles().getFile(0);
            String filename = file.getFileName();
            String ContentType = file.getContentType();
            System.out.println("ContentType"+ContentType);
            //获取文本信息
            String uname = smartUpload.getRequest().getParameter("uname");
            System.out.println("uname="+uname);

            //5.指定上传的路径
            String uploadpath = "/uploadfiles/" + filename;
            System.out.println("uploadpath="+uploadpath);
            //6.保存到指定位置
            file.saveAs(uploadpath, File.SAVEAS_VIRTUAL);

            //7.跳转成功页面
            req.setAttribute("filename", filename);
            req.getRequestDispatcher("success.jsp").forward(req, resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
    }
}

以下为jsp文件
 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>success.jsp  --smartupload</h1>
    <h2>${message}</h2>
    <a href="downloadimg?filename=${filename}">下载</a>
    <img src="uploadfiles/${filename}"/>
</body>
</html>

方法2--fileupload

上传主要两个文件:一个是Servlet文件,还有一个是jsp文件

 以下为Servlet文件

注意:经过测试发现存储在非临时硬盘上,速度非常慢,会出现HTML页面渲染完成,文件没有上传或执行中的情况,实际开发建议响应走临时,存储服务器走异步。

package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet(urlPatterns = "/uploadtest2")
public class UploadServlet2 extends HttpServlet {

    // 上传配置
    private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3;  // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
    private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

    // 上传文件存储目录
    private static final String UPLOAD_DIRECTORY = "upload";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 检测是否为多媒体上传
        if (!ServletFileUpload.isMultipartContent(request)) {
            // 如果不是则停止
            PrintWriter writer = response.getWriter();
            writer.println("Error: 表单必须包含 enctype=multipart/form-data");
            writer.flush();
            return;
        }
        // 配置上传参数
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

        // 设置内存临界值 - 超过后将产生临时文件并存储于临时目录中
        diskFileItemFactory.setSizeThreshold(MEMORY_THRESHOLD);
        // 设置临时存储目录
        diskFileItemFactory.setRepository(new File(System.getProperty("java.io.tmpdir")));

        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        // 设置最大文件上传值
        servletFileUpload.setFileSizeMax(MAX_FILE_SIZE);

        // 设置最大请求值 (包含文件和表单数据)
        servletFileUpload.setSizeMax(MAX_REQUEST_SIZE);
        servletFileUpload.setHeaderEncoding("UTF-8");

        // 构造临时路径来存储上传的文件
        // 这个路径相对当前应用的目录
        String uploadPath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;
        /*System.out.println("getServletContext().getRealPath(\"/\")=\n"+getServletContext().getRealPath("/"));
        System.out.println("File.separator="+File.separator);
        System.out.println("UPLOAD_DIRECTORY="+UPLOAD_DIRECTORY);*/
        // 如果目录不存在则创建
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
//        //构造路径来存储上传的文件
//        String uploadfilesPath = this.getClass().getClassLoader().getResource("/").getPath()+
//                ".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+
//                "web"+File.separator+"uploadfiles";
        System.out.println("classPath="+uploadfilesPath);
//        File uploadDir2 = new File(uploadfilesPath);
//        // 如果目录不存在则创建
//        if (!uploadDir2.exists()) {
//            uploadDir2.mkdir();
//        }

        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = servletFileUpload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {

                        String fileName = new File(item.getName()).getName();
                        String filePath = uploadPath + File.separator + fileName;
                        File storeFile = new File(filePath);
                        // 在控制台输出文件的上传路径
                        // System.out.println(filePath);
                        // System.out.println(uploadPath +"\n"+ File.separator +"\n"+ fileName);

                       System.out.println("uploadPath="+uploadPath);
                        System.out.println("File.separator="+File.separator);
                        System.out.println("fileName="+fileName);
                        System.out.println(storeFile);
//                         保存文件到硬盘
                        item.write(storeFile);




//                        String fileName2 = new File(item.getName()).getName();
//                        //指定上传的路径
//                        File uploadPath2=new File(uploadfilesPath+File.separator+fileName2);
//                        System.out.println("uploadPath2="+uploadPath2);
//                        //保存到指定位置
//                        item.write(uploadPath2);
//                        request.setAttribute("fileName2",
//                                fileName2);

                        //                        跳转成功页面
                        request.setAttribute("message",
                                "文件上传成功!");
                        request.setAttribute("fileName",
                                fileName);
//                        request.setAttribute("fileName2",
//                                fileName2);

                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }

        getServletContext().getRequestDispatcher("/message.jsp").forward(
                request, response);

        //存储文件相对路径
        /*String srcPath = System.getProperty("user.dir")+"\\src";
        String webPath = System.getProperty("user.dir")+"\\web";
        System.out.println("webPath="+webPath);
        System.out.println("srcPath="+srcPath);*/
//        String filePath2=webPath+ File.separator+"/uploadfiles";
//

       /* String uploadfilesPath = this.getClass().getClassLoader().getResource("/").getPath()+
                ".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+".."+File.separator+
                "web"+File.separator+"uploadfiles";
//        System.out.println("classPath="+uploadfilesPath);
        File uploadDir2 = new File(uploadfilesPath);
        if (!uploadDir2.exists()) {
            uploadDir2.mkdir();
        }
        try {
            // 解析请求的内容提取文件数据
            @SuppressWarnings("unchecked")
            List<FileItem> formItems = servletFileUpload.parseRequest(request);

            if (formItems != null && formItems.size() > 0) {
                // 迭代表单数据
                for (FileItem item : formItems) {
                    // 处理不在表单中的字段
                    if (!item.isFormField()) {
                        String fileName2 = new File(item.getName()).getName();
                        //指定上传的路径
                        File uploadPath2=new File(uploadfilesPath+File.separator+fileName2);
                        System.out.println("uploadPath2="+uploadPath2);
                        //保存到指定位置
                        item.write(uploadPath2);
                        request.setAttribute("fileName2",
                                fileName2);
                    }
                }
            }
        } catch (Exception ex) {
            request.setAttribute("message",
                    "错误信息: " + ex.getMessage());
        }


        // 跳转到 message.jsp
        request.getRequestDispatcher("/message.jsp").forward(request, response);*/



//        test1(request);
//        test2(request);
//        kkb();
    }

//    private static void kkb() {
//        try {
//            //1.创建上传文件的对象
//            SmartUpload smartUpload=new SmartUpload();
//            //2.初始化上传操作
//            //i=int 字节 b1内存溢出部分是否输出到输出流:true
//            //s为响应错误页面.可以不指定    b:是否使用session
//            PageContext pageContext=JspFactory.getDefaultFactory()
//                    .getPageContext(this,req,resp,null,false,1024,true);
//            smartUpload.initialize(pageContext);
//            //2.1设置编码
            smartUpload.setCharset("utf-8");
        3.上传
//            smartUpload.upload();
        4.获取文件信息
//            File file =smartUpload.getFiles().getFile(0);
//            String fileName=file.getFileName();
//            String ContentType=file.getContentType();
//            //5.指定上传的路径
//            String uploadpath="/uploadfiles/"+fileName;
//            //6.保存到指定位置
//            file.saveAs(uploadpath,File.SAVEAS_VIRTUAL);
//            //7.跳转成功页面
//            req.setAttribute("filename",fileName);
//            req.getRequestDispatcher("success.jsp").forward(req,resp);
//        } catch (SmartUploadException e) {
//            e.printStackTrace();
//        }
//    }

    private static void test2(HttpServletRequest request) throws IOException {
        //哔哩哔哩黑马
        ServletInputStream servletInputStream= request.getInputStream();//请求正文输入流
        Integer len =-1;
        byte b[] =new byte[1024];
        while((len=servletInputStream.read(b))!=-1){
//            System.out.println(new String(b,0,len));
        }
        servletInputStream.close();
    }

    private static void test1(HttpServletRequest res) {
        /**
         * getParameter只能获取正文为
         * application/x-www-form-urlencoded
         * 类型的数据
        */
        String name = res.getParameter("name");
        String pic = res.getParameter("pic");
        System.out.println("name="+name);
        System.out.println("pic="+pic);
    }
}

以下为jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h2>message.jsp --fileupload</h2>
<h2>${message}</h2>
<a href="downimg?filename=${filename}">下载</a><br>
指定位置存储位置
<img src="uploadfiles/${fileName2}"/><hr>
指定临时存储位置
<img src="upload/${fileName}"/>

</body>
</html>

文件下载

以下为Servlet文件

package servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

@WebServlet(urlPatterns = "/downloadimg")
public class DownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename=req.getParameter("filename");
        String path = "/uploadfiles/" + filename;
        System.out.println(path);
        //设置响应的头信息和响应的类型:
        resp.setContentType("application/octet-stream");
        //resp.addHeader("Content-Disposition","attachment;filename="+filename);
        resp.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"UTF-8"));
        //跳转页面
        req.getRequestDispatcher(path).forward(req,resp);
        //清空缓存区
        resp.flushBuffer();
    }
}

以下为jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>success.jsp  --smartupload</h1>
    <h2>${message}</h2>
    <a href="downloadimg?filename=${filename}">下载</a>
    <img src="uploadfiles/${filename}"/>
</body>
</html>

以上为上传下载实例

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Servlet文件功能可以通过使用注解@MultipartConfig将Servlet标识为支持文件,然后将multipart/form-data的POST请求封装成Part对象,通过Part对象对上文件进行操作。以下是一个文件Servlet示例代码: ```java @WebServlet("/uploadServlet") @MultipartConfig // 如果是文件,必须要设置该注解! public class UploadServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("文件..."); // 设置请求的编码格式 req.setCharacterEncoding("UTF-8"); // 获取普通表单项(获取参数) String uname = req.getParameter("uname"); // 表单中表单元素的name属性值 System.out.println("uname: " + uname); // 获取Part对象(Servlet将multipart/form-data的POST请求封装成Part对象) Part part = req.getPart("myfile"); // 通过Part对象得到上文件名 String fileName = part.getSubmittedFileName(); System.out.println("上文件名:" + fileName); // 得到文件存放的路径 String filePath = req.getServletContext().getRealPath("/"); System.out.println("文件存放路径:" + filePath); // 上文件到指定目录 part.write(filePath + "/" + fileName); } } ``` 而文件下载功能可以通过设置download属性来实现。以下是一个文件下载的JSP页面的示例代码: ```html <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>文件下载</title> </head> <body> <!-- 浏览器能够识别的资源 --> <a href="download/hello.txt">文本文件</a> <a href="download/pic.jpg">图片文件</a> <!-- 浏览器不能够识别的资源 --> <a href="download/zzz.rar">压缩文件</a> <hr> <a href="download/hello.txt" download>文本文件</a> <a href="download/pic.jpg" download="test.png">图片文件</a> <hr> <form action="downloadServlet"> 文件名:<input type="text" name="fileName" placeholder="请输入要下载文件名"> <button>下载</button> </form> </body> </html> ``` 以上是文件下载的实现方法,你可以根据需要进行调整和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值