使用Ajax异步请求上传文件

小兔叽 可爱的博主

时间: 2020-10-14 阅读: 279 字数:7325

{}
ajax请求可以让页面局部刷新(也就是让页面不进行跳转),在很多时候需要用到ajax请求,比如验证用户名是否存在....等等

Ajax上传文件实现

##1. 认识FormData对象

FormData是Html5新加进来的一个类,可以模拟表单数据

函数 解释
FormData (optional HTMLFormElement form) (可选) 一个HTML表单元素,可以包含任何形式的表单控件,包括文件输入框.

1. 实现Ajax上传,js代码

  $(function(){
            $("#file").change(function(){ 
            var img = document.myForm.img.files[0];    
            alert(img)
            var fm = new FormData();
            fm.append('img', img);
            $.ajax({            
            url: 'http://localhost:8080/sjx1boke/UserTextServlet?method=upade',           
            type: 'POST',            
            data: fm,            
            contentType: false, //禁止设置请求类型
            processData: false, //禁止jquery对DAta数据的处理,默认会处理
            //禁止的原因是,FormData已经帮我们做了处理
            dataType: 'json', 
            success: function (result) {        //测试是否成功
            alert(result.relst);
                            }
                        });
                    });
            })

<h2>2. 实现Ajax上传,html代码</h2>

<html>
    <head>
        <meta charset="utf-8">
        <title></title>
        <script type="text/javascript" src="js/jquery-3.3.1.js">
              <style>  
                /*样式1*/  
                .a-upload {  
                    padding: 4px 10px;  
                    height: 20px;  
                    line-height: 20px;  
                    position: relative;  
                    cursor: pointer;  
                    color: #888;  
                    background: #fafafa;  
                    border: 1px solid #ddd;  
                    border-radius: 4px;  
                    overflow: hidden;  
                    display: inline-block;  
                    *display: inline;  
                    *zoom: 1  
                }  
                .a-upload  input {  
                    position: absolute;  
                    font-size: 100px;  
                    right: 0;  
                    top: 0;  
                    opacity: 0;  
                    filter: alpha(opacity=0);  
                    cursor: pointer  
                }  
                .a-upload:hover {  
                    color: #444;  
                    background: #eee;  
                    border-color: #ccc;  
                    text-decoration: none  
                }  
                /*样式2*/  
                .file {  
                    position: relative;  
                    display: inline-block;  
                    background: #D0EEFF;  
                    border: 1px solid #99D3F5;  
                    border-radius: 4px;  
                    padding: 4px 12px;  
                    overflow: hidden;  
                    color: #1E88C7;  
                    text-decoration: none;  
                    text-indent: 0;  
                    line-height: 20px;  
                }  
                .file input {  
                    position: absolute;  
                    font-size: 100px;  
                    right: 0;  
                    top: 0;  
                    opacity: 0;  
                }  
                .file:hover {  
                    background: #AADFFD;  
                    border-color: #78C3F3;  
                    color: #004974;  
                    text-decoration: none;  
                }  
            </style>  
    </head>
<body style="padding: 10px">  
<form name="myForm"  enctype="multipart/form-data">
    <a href="javascript:;" class="a-upload">  
        <input id="file" type="file" value="上传图片" name="img">上传图片
    </a>  
</form>
</body>  
</html>  

网页效果

<img src='http://localhost:8080/sjx1boke/upload/9c05e0ca31ae4980be5716c96b50d114_07.png&#39;>

后台代码

 public void upade(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // 1、先判断是否是上传的协议
            boolean isMultipart = ServletFileUpload.isMultipartContent(request);
            if (isMultipart) {
                try {
                    // 2、创建一个文件工厂FileItemFactory
                    FileItemFactory fileItemFactory = new DiskFileItemFactory();
                    // 3、创建一个用来解析上传协议的类ServletFileUpload
                    ServletFileUpload fileUpload = new ServletFileUpload(fileItemFactory);
                    String src=null;
                    // 4、解析request数据
                    List<FileItem> fileItems = fileUpload.parseRequest(request);
                    System.out.println("表单项个数:" + fileItems.size());
                    // 5、遍历处理每一个表单项
                    for (FileItem fileItem : fileItems) {
                        // 判断是否是普通的表单项,还是上传的文件项
                        if (fileItem.isFormField()) {
                            System.out.println(fileItem.isFormField());
                            // 获取表单项name的值
                            System.out.println(fileItem.getFieldName());
                            // 获取表单项值
                            System.out.println(fileItem.getString());
                        } else {
                            // 打印测试
                            System.out.println(fileItem.isFormField());
                            System.out.println(fileItem.getFieldName());
                            // 获取文件名
                            System.out.println(fileItem.getName());
                            //生成uuid名字
                            String uuid = UUID.randomUUID().toString().replaceAll("-","");
                            System.out.println(uuid);
                            // 保存到工程中upload目录下
                            File f = new File(getServletContext().getRealPath("/upload") + "/" + 
                                             uuid + "_" + fileItem.getName());
                        src =uuid + "_" + fileItem.getName();
                        System.out.println("file 路径:" + f);
                        // 把文件写入到指定路径。
                        fileItem.write(f);
                    }
                }
                response.getWriter().write("{\"relst\" : \""+1+"\",\"src\" : \""+src+"\"}");
            } catch (Exception e) {
                e.printStackTrace();
                response.getWriter().write("{\"relst\" : \""+0+"\"}");
            }

} else {
            System.out.println("不是合法的文件上传!!");
            response.getWriter().write("{\"relst\" : \""+0+"\",\"src\" : \""+0+"\"}");
        }    
本文章网址:https://www.sjxi.cn/detil/1f80505326e147eabceb7bdf6967431d

最新评论

当前未登陆哦
登陆后才可评论哦

湘ICP备2021009447号

×

(穷逼博主)在线接单

QQ: 1164453243

邮箱: abcdsjx@126.com

前端项目代做
前后端分离
Python 爬虫脚本
Java 后台开发
各种脚本编写
服务器搭建
个人博客搭建
Web 应用开发
Chrome 插件编写
Bug 修复