Springmvc模式上传和下载与enctype对比

一般表单数据分为两类

enctype带文件上传的表单和不带enctype的传统表单,这两种提交的数据有着不同的样式,并且上传文件只能使用enctype。

@Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");
    //服务器存储文件的地址,需自己定义
    String savepath = this.getServletContext().getRealPath("/upload");
    System.out.println(savepath);
    //如果文件不存在,需要先进行判断,并创建,否则会出现空文件报错
    File file=new File(savepath);
    if(!file.exists()){
      file.mkdir();
    }
    //工具类commons-fileupload包创建工厂对象
    DiskFileItemFactory itemFactory=new DiskFileItemFactory();
    ServletFileUpload  upload=new ServletFileUpload(itemFactory);
    //判断是不是传统表单
    if(!ServletFileUpload.isMultipartContent(req)){
      System.out.println("是传统的表单 没有上传功能");
      return;
    }

    try {
      //表单的各项数据对象,封装成集合
      List<FileItem> list = upload.parseRequest(req);
      for(FileItem item:list){

        //是普通的表单数据
        if(item.isFormField()){
          String fieldName = item.getFieldName();
          String value = item.getString("utf-8");
          System.out.println(fieldName+"  "+value);
        }else {
          String filename = item.getName();//上传的文件名字
          if(filename==null||filename.trim().equals("")){
            // 当前上传的文件为空
            continue;
          }
          System.out.println(filename);
          //得到文件的名字
          filename = filename.substring(filename.lastIndexOf("\\")+1);

          InputStream in = item.getInputStream();

          OutputStream out=new FileOutputStream(savepath+"\\"+filename);

          byte[] buf=new byte[1024];
          int len=0;
          while((len=in.read(buf))>0){
            out.write(buf,0,len);
          }
          in.close();
          out.close();
        }

      }
    } catch (FileUploadException e) {
      e.printStackTrace();
    }

  req.getRequestDispatcher("/downloadlist").forward(req,resp);
  }

上传文件的大致上,是将提交的文件转存到服务器端的一个文件目录下。然后转发到展示页面供选择。

下载文件的一些设置

@Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    req.setCharacterEncoding("utf-8");
    resp.setContentType("text/html;charset=utf-8");
    //获取前台文件所展示的文件名称和存储目录下的名称要一致,方便写参数下载。
    String fileName= req.getParameter("file");

    //先获取上传目录路径
    String basePath = getServletContext().getRealPath("/upload");

    //如果文件名是中文,需要进行url编码,此操作是为了避免不同浏览器的下载页面下文件乱码的情况
    String agent = req.getHeader("User-Agent");
    String filenameEncoder = "";
    if (agent.contains("MSIE")) {
      // IE浏览器
      filenameEncoder = URLEncoder.encode(fileName, "utf-8");
      filenameEncoder = filenameEncoder.replace("+", " ");
    } else if (agent.contains("Firefox")) {
      // 火狐浏览器
      BASE64Encoder base64Encoder = new BASE64Encoder();
      filenameEncoder = "=?utf-8?B?"
          + base64Encoder.encode(fileName.getBytes("utf-8")) + "?=";
    } else {
      // 其它浏览器
      filenameEncoder = URLEncoder.encode(fileName, "utf-8");
    }


    //设置下载的响应头
    resp.setHeader("content-disposition", "attachment;fileName="+filenameEncoder);//此filenameEncoder必须经过转码处理
    //获取一个文件输入流
    InputStream is = new FileInputStream(new File(basePath,fileName));
    //获取response字节流
    OutputStream out = resp.getOutputStream();
    byte[] b= new byte[1024];
    int len =-1;
    while((len=is.read(b))!=-1){
      out.write(b,0,len);
    }
    //关闭流
    out.close();
    is.close();
  }

理。

还需要提前设置对浏览器的响应头,告知浏览器是一个文件。

resp.setHeader(“content-disposition”, “attachment;fileName=”+filenameEncoder);

接触了springmvc模式后,对上面的上传与下载进行优化,

此处上传的功能依旧是采用表格上传。文件格式依旧是

后台则是

@RequestMapping("/upload")
  public String upload(MultipartFile file,String userName,HttpServletRequest request) throws IOException {
    String filename = file.getOriginalFilename();

    String suffix = filename.substring(filename.lastIndexOf("."));

    if(suffix.equalsIgnoreCase(".jpg")){
      String uuid = UUID.randomUUID().toString();
      //FileUtils.copyInputStreamToFile(file.getInputStream(),new File("E://"+uuid+suffix));

      file.transferTo(new File("D://"+System.currentTimeMillis()+suffix));//位置存储在硬盘上
//      file.transferTo(new File(request.getServletContext().getRealPath("/")+"static/userImages/"+file));
//      存储在项目里的目录下
      request.setAttribute("result","上传成功");
      return "/result.jsp";
    }else{
      request.setAttribute("result","上传失败");
      return "/result.jsp";
    }
  }

相比之前的传统式上传,springmvc模式下封装了许多繁琐的过程,通过transferTo即可实现一些相应的操作

而下载也是相应的简化了许多

@RequestMapping("/download")
  public void download(String filename, HttpServletResponse response, HttpServletRequest request) throws IOException {
    response.setHeader("content-disposition","attachment;filename="+filename);

    ServletOutputStream outputStream = response.getOutputStream();

    String path = request.getServletContext().getRealPath("images");

    File file = new File(path,filename);

    byte[] bytes = FileUtils.readFileToByteArray(file);

    outputStream.write(bytes);

    outputStream.close();
  }

一般框架会省去许多重复性的工作,但底层的基本原理还是要清楚过程

最新2020整理收集的一些高频面试题(都整理成文档),有很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解,也有详细的学习规划图,面试题整理等,需要获取这些内容的朋友请加Q君样:11604713672

猜你喜欢

转载自blog.csdn.net/weixin_51495453/article/details/112371048