上传和下载

下载路径:https://pan.baidu.com/s/1yKTH-rDfEBAHk7zFI9T_Mw

相关代码:

前端代码:

<%@ 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>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

    <span style="color:red;">${error}</span>

    <form action="/down" method="post" enctype="multipart/form-data">

    姓名:<input type="text" name="name"/><br>

    年龄:<input type="text" name="age"/><br>

    上传头像:<input type="file" name="images"/><br>

    <input type="submit" name="btn" value="注册"/>

    </form>

</body>

</html>

 

 

 

异常机制:

package download_upload.download;

public class wenjianexception extends RuntimeException{

    public wenjianexception() {

        super();

        // TODO Auto-generated constructor stub

    }

    public wenjianexception(String message, Throwable cause) {

        super(message, cause);

        // TODO Auto-generated constructor stub

    }

    public wenjianexception(String message) {

        super(message);

        // TODO Auto-generated constructor stub

    }

   

}

 

user类

package download_upload.download;

import lombok.Data;

@Data

public class user {

      private String name;

      private int age;

      private String img;

}

utils工具类

package download_upload.download;

 

import java.io.File;

import java.util.List;

import java.util.Map;

import java.util.UUID;

 

import javax.naming.SizeLimitExceededException;

import javax.servlet.http.HttpServletRequest;

 

import org.apache.commons.fileupload.FileItem;

import org.apache.commons.fileupload.FileUploadBase.FileSizeLimitExceededException;

import org.apache.commons.fileupload.FileUploadException;

import org.apache.commons.fileupload.disk.DiskFileItemFactory;

import org.apache.commons.fileupload.servlet.ServletFileUpload;

import org.apache.commons.io.FilenameUtils;

 

public class utils {

      public static void wenjian(HttpServletRequest req,Map<String,Object> map)

      {

        

          boolean isMultipart = ServletFileUpload.isMultipartContent(req);

          // Create a factory for disk-based file items//创建基于磁盘的文件项的工厂

          DiskFileItemFactory factory = new DiskFileItemFactory();

          factory.setSizeThreshold(1024*500);

          factory.setRepository(new File("D:/"));

          // Create a new file upload handler

          //创建新文件上传处理程序

          ServletFileUpload upload = new ServletFileUpload(factory);

        upload.setFileSizeMax(500*1024);

        upload.setSizeMax(800*1024);

          // Parse the request

          //解析请求

          try {

              List <FileItem>  items = upload.parseRequest(req);

              for (FileItem item : items) {

                  if (item.isFormField()) {

                     // String fieldName = item.getFieldName();

                     // long sizeInBytes = item.getSize();

                      //String wenjian=item.getString();

                      //System.out.println(fieldName+","+sizeInBytes+","+wenjian);

                      //System.out.println("-------------------------------");

                      map.put(item.getFieldName(), item.getString().toString());

                  }

                  else {

                          //String fieldName = item.getFieldName();

                          //System.out.println(fieldName);

                         // long sizeInBytes = item.getSize();

                          //String wenjian=item.getString("UTF-8");

                          //System.out.println(fieldName+","+sizeInBytes+","+wenjian);

                          System.out.println("-------------------------------");

                          try {

                                  if(!item.getContentType().startsWith("image/"))

                                  {

                                      

                                      throw new wenjianexception("亲!您上传的文件格式有误,请重新上传!!!!");

                                  }

                                  else {

                                      String filename=UUID.randomUUID().toString()+"."+FilenameUtils.getExtension(item.getName());

                                       item.write(new File(new File(req.getServletContext().getRealPath("images")),filename));

                                       map.put(item.getFieldName(), filename);

                                   }

                              }catch(wenjianexception e) {

                              throw e;

                          }

                          catch(FileSizeLimitExceededException e) {

                              throw new wenjianexception("亲,你的文件超过了500kb,请重新上传");

                          }catch(SizeLimitExceededException e) {

                              throw new wenjianexception("亲,您的总文件请求超过800kb,请重新上传");

                          }

                          catch (Exception e) {

                              // TODO Auto-generated catch block

                              e.printStackTrace();

                          }

                  }

              }

          } catch (FileUploadException e) {

              // TODO Auto-generated catch block

              e.printStackTrace();

          }

      }

}

 

servlet类

package download_upload.download;

 

import java.io.File;

import java.io.IOException;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.UUID;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

 

@WebServlet("/down")

public class download extends HttpServlet{

 

    /**

     *

     */

    private static final long serialVersionUID = 1L;

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        // TODO Auto-generated method stub

        req.setCharacterEncoding("UTF-8");

        try {

            user u=new user();

            Map<String, Object> map=new HashMap<>();

            utils.wenjian(req,map);

            u.setName(map.get("name").toString());

            u.setAge(Integer.valueOf( map.get("age").toString()));

            u.setImg(map.get("images").toString());

            System.out.println(u);

            req.setAttribute("error","注册成功");

            req.getRequestDispatcher("/download.jsp").forward(req, resp);

        } catch (wenjianexception e) {

            // TODO: handle exception

            req.setAttribute("error",e.getMessage());

            req.getRequestDispatcher("/download.jsp").forward(req, resp);

        }

        

    }

}

 

使用uuid后的显示结果

下载功能的实现

前端代码

<%@ 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>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Insert title here</title>

</head>

<body>

<h1>资源下载</h1>

    <a href="/upload?filename=洲洲.zip">洲洲.zip</a><br>

    <a href="/upload?filename=smis.zip">smis.zip</a>

</body>

</html>

 

后台代码:

package download_upload.upload;

import java.io.File;

import java.io.IOException;

importjava.net.URLEncoder;

import java.nio.file.Files;

import java.nio.file.Paths;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/upload")

public class upload extends HttpServlet{

    /**

     *

     */

    private static final long serialVersionUID = 1L;

    @Override

    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

     // TODO Auto-generated method stub

     resp.setContentType("application/x-msdownload");

     req.setCharacterEncoding("UTF-8");

     String name=req.getHeader("User-Agent");

     

     String filename=req.getParameter("filename");

     if(name.contains("MSIE"))

     {

         resp.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));

     }else {

         resp.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("UTF-8"),"ISO-8859-1"));

     }

     System.out.println(filename);

     String path=req.getServletContext().getRealPath("/WEB-INF/download");

     File file=new File(path, filename);

     ServletOutputStream out=resp.getOutputStream();

     Files.copy(Paths.get(file.getAbsolutePath()),out);

    }

}

整体结构图解:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值