【JavaWeb】ajax异步文件上传

1. html部分

    <form id="uploadForm" enctype="multipart/form-data">
        <input type="file" name="file" /> <input type="file" name="file" />
        <input type="button" value="上传" id="upload" />
    </form>

2. js部分

$(document).ready(function(){
        $("#upload").click(function(){
            $.ajax({
            url: 'upload.do',
                 type: 'POST',
                 cache: false,
                 data:new FormData($('#uploadForm')[0]),//h5的DataForm对象
                 dataType:"json",
                 processData: false,
                 contentType: false,
                 success:function(data){
                    alert(data.status);
                 }
            })  
        })
    })

3. java部分

@ResponseBody
    @RequestMapping("upload.do")
    public String upload(String un,@RequestParam("file") MultipartFile[] file, HttpServletRequest req)
            throws IllegalStateException, IOException {
        String basePath = "C:\WebFile\yao2san\";
        boolean isSuccess = false;
        for (MultipartFile f : file) {
            String path = "";
            if (!f.isEmpty()) {
                if (f.getOriginalFilename().endsWith("txt"))
                    path = basePath + "doc"; 
                else if (f.getOriginalFilename().endsWith("jpg") || f.getOriginalFilename().endsWith("gif")
                        || f.getOriginalFilename().endsWith("png"))
                    path = basePath + "img";
                else
                    path = basePath + "other";
                String fileName = f.getOriginalFilename();
                File tarFile = new File(path, fileName);
                f.transferTo(tarFile);
                isSuccess = true;
            }
        }
        return "{"status":"+isSuccess+"}";
    }
原文地址:https://www.cnblogs.com/cnsec/p/13286759.html