springmvc文件上传

 

 

 

 

文件上传

导包

需要导入文件上传的两个jar

index.jsp

注意使用文件上传的时候,需要将enctype更改为文件上传的编码

springmvc配置文件上传

注意:id不能变

<bean id="multipartResolver"

   class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

      <property name="maxUploadSize" value="51200000"></property>

   </bean>

controller

controller中定义方法,获得上传的文件,并上传到tomcat服务器上

@RequestMapping(value = "/upload", method = RequestMethod.POST)

   public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) {

      String filename = file.getOriginalFilename();

      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmssSS");

      String format = simpleDateFormat.format(new Date());

      filename = format + filename;

      String path = request.getServletContext().getRealPath("/upload");

      File file2 = new File(path);

      if(!file2.exists()){

        file2.mkdir();

      }

      System.out.println(filename);

      try {

        file.transferTo(new File(path, filename));

      } catch (IllegalStateException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

      } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

      }

      return "";

   }

上传测试

在后台打印上传的图片的名称

tomcat中找到上传的图片

在浏览器上访问一下该图片

 

posted @ 2019-08-28 10:29  emmmmmm哇咔咔  阅读(101)  评论(0编辑  收藏  举报