springMVC文件上传

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;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值