Spring MVC文件上传

来源:互联网 发布:开开贷网络借钱 编辑:程序博客网 时间:2024/06/13 18:12

JSP部分

<!-- 提交方式必须为POST --><!-- form表单必须设置enctype="multipart/form-data"属性 --><form action="${pageContext.request.contextPath}/fileUploading" method="post" enctype="multipart/form-data">        <input type="file" name="fil"></input>        <input type="submit" value="上传"></input></form>

在springMVC-servlet.xml中配置上传解析器

    <!-- 上传解析器 -->    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <!-- 最大字节限制 -->        <property name="maxUploadSize" value="10240000"></property>        <!-- 最小字节限制 -->        <property name="maxInMemorySize">              <value>1</value>          </property>      </bean>

Spring后台处理

    @RequestMapping(value="/fileUploading",method=RequestMethod.POST)    public String fileUploading(HttpServletRequest request){        try{        //恢复Request本身        MultipartHttpServletRequest mhsr = (MultipartHttpServletRequest) request;        //获取文件        MultipartFile mf = mhsr.getFile("fil");        byte[] bytes = mf.getBytes();        //文件名        String oriFilename = mf.getOriginalFilename();        //后缀名  .XXXX        String lastname = oriFilename.substring(oriFilename.lastIndexOf("."));        //new文件对象        File file = new File(StringName.stringName(request.getSession().getServletContext().getRealPath("/"),lastname));        //OUT 写入服务器中        FileOutputStream fos = new FileOutputStream(file);        fos.write(bytes);        fos.flush();        fos.close();        } catch(Exception e){            return "jsp/false";        }        return "jsp/true";    }

Util工具包,用来处理File存储路径

public class StringName {    private static Random random = new Random();    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");    public static String stringName(String webPath,String suffixName){        String name = sdf.format(new Date());        for(int i=1;i<=3;i++){            name+=random.nextInt(9);        }        return webPath+"WEB-INF\\file\\"+name+suffixName;    }}
1 0
原创粉丝点击