zoukankan      html  css  js  c++  java
  • 【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+"}";
        }
  • 相关阅读:
    mongodb的账户管理
    mongo备份与恢复
    mongo索引
    聚合aggregate
    07-【jsp基本了解】
    Servlet登录小案例
    06-【servletconfig、servletContext 】
    05-【session、cookie】
    jQuery
    04-【servlet转发和重定向】
  • 原文地址:https://www.cnblogs.com/cnsec/p/13286759.html
Copyright © 2011-2022 走看看