1

Jsp文件上传

 2 years ago
source link: https://jiang565745499.github.io/2020/05/29/java-jsp%E6%96%87%E4%BB%B6%E4%B8%8A%E4%BC%A0.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

需要两个jar包

commons-fileupload-1.4.jar

commons-io-2.7.jar

upload

@Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("UTF-8");
        //1 先判断上传的数据是否多段数据
        if(ServletFileUpload.isMultipartContent(req)){
            //创建FileItemFactory工厂实现类
            FileItemFactory fileItemFactory = new DiskFileItemFactory();
            //创建用于解析上传数据的工具类ServletFileUpload
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            //解析上传的数据,得到每一个表单项FileItem
            try {
                List<FileItem> fileItems = servletFileUpload.parseRequest(req);
                for (FileItem f:fileItems
                     ) {
                    if(f.isFormField()){
                        //普通表单项
                        System.out.println("表单项的name属性值"+f.getFieldName());
                        System.out.println("表单项的value属性值"+f.getString("UTF-8"));
                    }else{
                        //上传的文件
                        System.out.println("表单项的name属性值"+f.getFieldName());
                        System.out.println("上传的文件名"+f.getName());
                        f.write(new File("E:\\upload\\firstweb\\"+f.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

download

@Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取要下载的文件名
        String downloadFileName = "1.jpg";
        //读取要下载的文件内容
        ServletContext servletContext = getServletContext();
        //获取要下载的文件类型
        String mimeType = servletContext.getMimeType("/file/" + downloadFileName);
        //通过响应头告诉客户端返回的数据类型
        resp.setContentType(mimeType);
        //告诉客户端收到的数据用于下载
        //Content-Disposition 表示收到的数据怎么处理
        //attachment 表示附件,需要下载使用
        //filename 表示要下载的文件
        resp.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(downloadFileName,"UTF-8"));
        InputStream resourceAsStream = servletContext.getResourceAsStream("/file/" + downloadFileName);
        //获取响应的输出流
        OutputStream outputStream = resp.getOutputStream();
        //将输入流复制给输出流 回传给客户端
        IOUtils.copy(resourceAsStream,outputStream);
    }

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK