• javaweb简单的实现文件上传


     java代码:

    //  @RequestMapping(value = "/upload.do", method = RequestMethod.POST)
    @RequestMapping(value = "savefile", method = RequestMethod.POST)
    // 这里的MultipartFile对象变量名跟表单中的file类型的input标签的name相同,所以框架会自动用MultipartFile对象来接收上传过来的文件,当然也可以使用@RequestParam("img")指定其对应的参数名称
    public String upload(MultipartFile upfile, HttpSession session, HttpServletRequest request)
    throws Exception {
    // 如果没有文件上传,MultipartFile也不会为null,可以通过调用getSize()方法获取文件的大小来判断是否有上传文件
    if (upfile.getSize() > 0) {
    // 得到项目在服务器的真实根路径,如:/home/tomcat/webapp/项目名/images
    // String path = session.getServletContext().getRealPath("/");
    String path=request.getRealPath("/");
    // 得到文件的原始名称,如:美女.png
    String fileName = upfile.getOriginalFilename();
    // 通过文件的原始名称,可以对上传文件类型做限制,如:只能上传jpg和png的图片文件
    if (fileName.endsWith("jpg") || fileName.endsWith("png") || fileName.endsWith("txt")) {
    File file = new File(path, fileName);
    upfile.transferTo(file);
    return "/success.jsp";
    }
    }
    return "/error.jsp";
    }

    注意事项:

    1:文件上传表单要用post方式提交,并且要加上  enctype="multipart/form-data" ;

    2:后台要用文件类型接收文件,不能用字符串接收,负责会报错;

    3:后台可用 String path=request.getRealPath("/"); 方法获取项目的路径,把文件放到相应的路径中。

    4:springmvc中有对上传文件的大小做限制 --> 

     5.多文件上传

      - 要使用multiple属性

      - 后台接受是一个数组

     

    数组接收的时候要注意使用 @RequestParam false

  • 相关阅读:
    1、接口测试全流程
    7、执行 suite 后,result.html 测试报告中,测试结果全部显示为通过原因分析
    6、Python 中 利用 openpyxl 读 写 excel 操作
    5、Python 基础类型 -- Dictionary 字典类型
    4、Python 基础类型 -- Tuple 元祖类型
    cp: omitting directory”错误的解释和解决办法
    c++ 之bind使用
    Linux查找–find命令
    lsof命令总结
    Linux查看端口、进程情况及kill进程
  • 原文地址:https://www.cnblogs.com/zhouheblog/p/9627387.html
Copyright © 2020-2023  润新知