Ajax上传文件问题(图片)

来源:互联网 发布:matlab编程与工程应用 编辑:程序博客网 时间:2024/06/07 09:08
 许多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处理文件需要定义。最后注意添加所需包。

原创粉丝点击