Ajax上传文件问题(图片)

 许多web项目都需要使用表单上传文件,之前一只使用表单直接上传,今天试下使用Ajax将表单文件上传,按照之前在form中添加 enctype="multipart/form-data"不能实现上传,后折腾好久得以解决。

前台表单内容,包含text输入框和问价输入框,不需要使用enctype属性:

<form class="form-horizontal" id="fromuserud">
    姓    名 <input type="text" name="aeName" class="form-control" id="aeName_update" placeholder="请输入姓名">    
    上传头像 <input type="file"  name="ae_photourl">
    <button type="button" id="user_update">更新</button>
</form>

js中ajax主要内容:

$("#user_update").click(function(){
var date=$("#fromuserud")[0];  //获取表单中的值
var formData = new FormData(date);  //使用FormData()处理表单中的值

var formData = new FormData(date); 
    $.ajax({
        url:"/userchange/"+id,  //发送的URL
        type:"POST",        //类型
        data:formData,      //将数据发送
        async: false,       //是否同步,否
            cache: false,       //是否缓存,否
            contentType: false,     //需要使用
            processData: false,     //需要使用
        success:function(result){
        //发送成功后需要执行的动作
        }
    });
});

后台控制器的代码:

@ResponseBody
@RequestMapping(value = "/userchange/{aeId}", method = RequestMethod.POST)
public Msg update(User user, HttpServletRequest request,@PathVariable("aeId") Integer aeId,
        @RequestParam(value = "ae_photourl", required = false) MultipartFile attach) {

        String photo = null;    //定义图片存储路径
        //存储图片过程
        if (!attach.isEmpty()) {
            String path = request.getSession().getServletContext().getRealPath("static" + File.separator + "images");
            String oldFileName = attach.getOriginalFilename();
            String prefix = FilenameUtils.getExtension(oldFileName);
            int filesize = 4000000;
            if (attach.getSize() > filesize) {
                return Msg.fail();
            }
            if ((prefix.equalsIgnoreCase("jpg")) || (prefix.equalsIgnoreCase("png"))
                    || (prefix.equalsIgnoreCase("jpeg")) || (prefix.equalsIgnoreCase("pneg"))) {
                String fileName = RandomUtils.nextInt(1000000) + "." + prefix;
                File targetFile = new File(path, fileName);
                if (!targetFile.exists()) {
                    targetFile.mkdirs();
                }
                try {
                    attach.transferTo(targetFile);
                } catch (Exception e) {
                    return Msg.fail();
                }
                photo = fileName;
            } else {
                return Msg.fail();
            }
        }
        user.setAePhotourl(photo);
        userService.update(user);
        return Msg.success();
    }

其中Msg是返回成功后的信息类。主要是注意定义方法那,
@ResponseBody
@RequestMapping(value = “/userchange/{aeId}”, method = RequestMethod.POST)
public Msg update(User user, HttpServletRequest request,@PathVariable(“aeId”) Integer aeId,
@RequestParam(value = “ae_photourl”, required = false)MultipartFile attach) {}
其中@PathVariable提取发送过来的aeId值的作用,MultipartFile处理文件需要定义。最后注意添加所需包。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值