Spring MVC文件上传

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值