Ajax上传文件

来源:互联网 发布:数据挖掘十大算法 知乎 编辑:程序博客网 时间:2024/05/18 11:26

在使用Ajax提交表单的时候可能会遇到上传文件的情况,可以使用ajaxFileUpload这个JQuery插件来搞定文件的上传。

HTML:

<input type="file" id="file" name="file" class="form-control" onchange="preImg(this.id,'imgPre');"/>

<input type="button" value="确认上传" onclick="ajaxFileUpload()"/>

JS:

/* 图片上传 */
function ajaxFileUpload() {
// 执行上传文件操作的函数
$.ajaxFileUpload({
url : path + '/admin/item/fileUpload',
secureuri : false, // 是否启用安全提交,默认为false
fileElementId : 'file', // 文件选择框的id属性
dataType : 'text', // 服务器返回的格式,可以是json或xml等
success : function(data, status) { // 服务器响应成功时的处理函数
if (data.code == 0) { 
$("#fileInfo").html("上传成功.");
} else {
$("#fileInfo").html("上传失败.");
}
},
error : function(data, status, e) {
$("#fileInfo").html("上传失败,请重试.");
}
});
}

后台保存:

 @ResponseBody
    @RequestMapping(value = "/item/fileUpload")
    public String addUser(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
        String message = null;


        if (file.isEmpty()) {
           
        } else {


            String format = DateUtil.format(DateUtil.getNow(), "yyyyMMdd");
            StringBuffer sb = new StringBuffer().append(File.separatorChar).append("fileUpload")
                .append(File.separatorChar).append("images").append(File.separatorChar).append("item")
                .append(File.separatorChar).append(format);
            String path = sb.toString();
            String realPath = request.getSession().getServletContext().getRealPath(path);


            long random = RandomUtil.getRandom(100000, 999999);
            String oriName = file.getOriginalFilename();
            String suffix = oriName.substring(oriName.lastIndexOf("."));
            String filename = DateUtil.getTime() + "" + random + suffix;


            try {
                FileUtils.copyInputStreamToFile(file.getInputStream(), new File(realPath, filename));
                message = "0`" + path + File.separatorChar + filename;
            } catch (IOException e) {
              
            }
        }
        return message;
    }

0 0