springMVC的上传文件,spring的transferTo保存文件方法

form表单
<form id="formfile" action="slideshowin" method="post" enctype="multipart/form-data">
    <input type="button" id="buttonf" οnclick="buttonfunction()" value="增加图片" />
<input type="file" name="file" οnchange="fileupload()" id="files" />
</form>
ajxa提交表单
function fileupload() {
获取表单,必须加[0]才能取到数据
   var formData =new FormData($("#formfile")[0]);
             $.ajax({
                 url: url,
                 type: "POST",
                 data: formData,
                 cache:false,
                 contentType: false,
                 processData: false,
                 success: function (dat) {
                     
                 },
                 error: function (dat) {
                     
                 }
             });
}
 
后台代码 spring的
MultipartFile类,必须在xml配置
 
<bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="209715200"/>
    <property name="defaultEncoding" value="UTF-8"/>
    <property name="resolveLazily" value="true"/>
</bean>
public String insert(@RequestParam("file")MultipartFile file,HttpServletRequest request)throws IOException {
                   if(!file.isEmpty()){
                        获取后缀名
                       String suffix =file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                       //设置允许上传文件类型
                       String suffixList = "jpg,png,ico,bmp,jpeg";
                       判断是否包含
                        if(suffixList.contains(suffix.trim().toLowerCase()))""){
                        保存文件的路径
                    String path = request.getSession().getServletContext().getRealPath("")+"slideImg/"+file.getOriginalFilename();
查看路径是否存在,不存在就创建
                            //image/jpeg
                           if(!new File(path).exists()){
                               new File(path).mkdirs();
           }
            spring的transferTo保存文件方法
           file.transferTo(new File(path));
           Slideshow slideshow=new Slideshow();
           slideshow.setSlideshowImg(file.getOriginalFilename());
           slideshow.setSlideshowState(0);
           slideshow.setSlideshowTime(new DataTime().getDatatime());
           slideshowService.insert(slideshow);
           return "成功!";
       }
       return "图片格式不正确!";
    }
    return "未选择图片!";
}


  • 6
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值