• springMVC上传图片


    一、需要导入springmvc文件上传的jar包,否则会出现异常java.lang.NoClassDefFoundError: org/apache/commons/fileupload/FileItemFactory

    二、创建上传页面form表单

    1 <form action="upload/uploadPic.do" method="post" enctype="multipart/form-data">
    2         <input type="file" name="pic">
    3         <br>
    4         <input type="submit" value="submit">
    5     </form>

    三、在springMVC配置文件中设置文件上传配置

    1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    2         <!-- 以字节为单位  -->
    3         <property name="maxUploadSize" value="1024000"></property>
    4     </bean>

    四、controller类的编写

     1 //跳转到表单页
     2     @RequestMapping("/toForm.do")
     3     public String toForm(){
     4         return "form1";
     5     }
     6     
     7     //文件上传
     8     @RequestMapping("/uploadPic.do")
     9     public String uploadPic(HttpServletRequest req) throws IOException{
    10         MultipartHttpServletRequest mr = (MultipartHttpServletRequest) req;
    11         //获得文件
    12         MultipartFile file = mr.getFile("pic");
    13         //获得文件字节数组
    14         byte[] bs = file.getBytes();
    15         //根据时间及随机数创建文件名
    16         String fileName = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
    17         Random random = new Random();
    18         for(int i = 0;i < 3;i++){
    19             fileName = fileName + random.nextInt(10);
    20         }
    21         //获得文件的原始文件名
    22         String originalFilename = file.getOriginalFilename();
    23         //对原始文件名切割获得后缀名
    24         String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    25         //获得项目路径
    26         String realPath = req.getSession().getServletContext().getRealPath("/");
    27         //创建字节输出流
    28         OutputStream out = new FileOutputStream(new File(realPath + "/upload/" + fileName + suffix));
    29         out.write(bs);
    30         out.flush();
    31         out.close();
    32         return "success";
    33     }
  • 相关阅读:
    C# RabbitMQ
    使用HttpClient和WebRequest时POST一个对象的写法
    HTTP中application/x-www-form-urlencoded字符说明
    MVC5 Entity Framework学习
    SQL Server安全
    Entity Framework查询
    COM 类工厂中 CLSID 为 {000209FF-0000-0000-C000-000000000046} 的组件失败,原因是出现以下错误: 80070005 拒绝访问。最新解决方案
    js中精度问题以及解决方案
    string.format
    t-sql对被除数为0&除数小于被除数结果为0&除法保留2位小数的处理
  • 原文地址:https://www.cnblogs.com/cat-fish6/p/8926350.html
Copyright © 2020-2023  润新知