springMVC文件上传

来源:互联网 发布:java求1到100的素数 编辑:程序博客网 时间:2024/05/04 12:06

spring-servlet.xml中配置:

   <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="UTF-8">
        <property name="maxUploadSize" value="100000000"/>
    </bean>
===============

页面:

<form name="form1" action="<%=request.getContextPath()%>/ArticleController.do?method=imgUpload" method="post"
        id="form1" enctype="multipart/form-data">
      <input type="file" name="imgFile" id="imgFile" title="选择图片"/>
      <input type="submit" value="上 传" id="btnUpload"/>
      <%
          String imgFilePath = null;
          if (request.getAttribute("imgFilePath") != null) {
              imgFilePath = (String) request.getAttribute("imgFilePath");
          }
      %>
      <input type="hidden" value="<%=imgFilePath%>" name="imgFilePath" id="imgFilePath"/>
  </form>

===============

@RequestMapping(params = {"method=imgUpload"})
    public ModelAndView imgUpload(@RequestParam("imgFile") MultipartFile imgFile, HttpServletRequest request) throws Exception {
        String imgFilePath = "upload/" + imgFile.getOriginalFilename();
        InputStream in = null;
        OutputStream out = null;
        try {
            in = new BufferedInputStream(imgFile.getInputStream(), 1024);
            out = new BufferedOutputStream(new FileOutputStream(request.getSession().getServletContext().getRealPath("/") + imgFilePath), 1024);
            //todo 暂时放到upload文件夹下
            byte[] buffer = new byte[1024];
            while (in.read(buffer) > 0) {
                out.write(buffer);
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (null != in) {
                in.close();
            }
            if (null != out) {
                out.close();
            }
        }
        Map<String, Object> model = new HashMap<String, Object>(2);
        model.put("imgFilePath",imgFilePath);
        ModelAndView modelAndView = new ModelAndView("/article/upload");
        modelAndView.addAllObjects(model);
        return modelAndView;
    }

原创粉丝点击