当前位置: 代码网 > it编程>前端脚本>Ajax > 使用AJAX实现上传文件

使用AJAX实现上传文件

2024年05月18日 Ajax 我要评论
本文实例为大家分享了使用ajax实现上传文件的具体代码,供大家参考,具体内容如下需求:在前端页面选择文件上传到服务器的指定位置前端代码<form id="uploadform" metho

本文实例为大家分享了使用ajax实现上传文件的具体代码,供大家参考,具体内容如下

需求:

在前端页面选择文件上传到服务器的指定位置

前端代码

<form   id="uploadform"  method="post" enctype="multipart/form-data">
   <label  >上传电子书</label>
   <input type="file"  name="file" >
   <button  id="upload" type="button"  name="button" >上传</button>
</form>
$("#upload").click(function () {
   var formdata = new formdata($('#uploadform')[0]);
   $.ajax({
    type: 'post',
    url: "https://****:8443/fileupload", //上传文件的请求路径必须是绝对路劲
     data: formdata,
     cache: false,
     processdata: false,
     contenttype: false,
      }).success(function (data) {
        console.log(data);
        alert("上传成功"+data);
        filename=data;
      }).error(function () {
         alert("上传失败");
     });
    });

首先创建一个formdata实例,也就是空对象,将页面中现有form表单将他初始化。通过ajax提交给后台

后端代码

@postmapping(value = "/fileupload")
    @responsebody
    public string  fileupload(@requestparam(value = "file") multipartfile file, model model, httpservletrequest request) {
        if (file.isempty()) {
            system.out.println("文件为空空");
        }
            string filename = file.getoriginalfilename();  // 文件名
            system.out.println(file.getoriginalfilename());
            string suffixname = filename.substring(filename.lastindexof("."));  // 后缀名
            string filepath = "c://pdf//"; // 上传后的路径
            filename = uuid.randomuuid() + suffixname; // 新文件名
            file dest = new file(filepath + filename);
            system.out.println("pdf文件路径为:"+dest.getpath());
            if (!dest.getparentfile().exists()) {
                dest.getparentfile().mkdirs();
                system.out.println("上传pdf文件+++++++++++");
                system.out.println("pdf文件路径为:"+dest.getpath());
            }
            try {
                file.transferto(dest);
            } catch (ioexception e) {
                e.printstacktrace();
            }
            string filename = "/pdf/" + filename;
          return filename;


    }

注意

1.@requestparam(value = “file”) 中的file需要和input中的name属性一致。
2.提交按钮类型type=“button”如果为“submit”的话,提交完数据会刷新一次页面。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com