ajax异步上传

ajax异步上传

定义Form

<form id="ff" enctype="multipart/form-data">
        <input type="text" name="name"><br>
        <input type="file" name="source"><img height="21px" id="sig"/><br>
        <input type="button" value="上传" onclick="upload();">
</form>
<img id="img"/>

定义ajax异步上传逻辑

function upload(){
    //准备上传:显示进度条
    document.getElementById("sig").src="/static/app_ajax/load.gif";
    //创建xhr
    xhr = new XMLHttpRequest();
    xhr.open("post","/ajax/up_logic/");
    //设置监听:获取文件上传进度
    xhr.upload.onprogress=function(a){//文件上传过程中不断触发
        console.log(a.loaded);
        console.log(a.total);
        if(a.loaded == a.total)
            document.getElementById("sig").src="/static/app_ajax/ok.gif";
    };
    //设置监听:获取响应内容
    xhr.onreadystatechange=function(){
        if(xhr.readyState==4){
            ret = xhr.responseText //接受响应内容:图片在服务器的存储位置(访问路径)
            console.log(ret)
            //回显上传的图片
            document.getElementById("img").src="/static/"+ret;
        }
    }
    //FormData(form的dom对象)
    xhr.send(new FormData(document.forms[0])) //发送请求,携带form的所有数据
}

定义Controller,接受上传的文件

方式照旧

补充:client可以可以通过jquery提供的方法$.ajax()完成上传

$.ajax({type:"post",
        data:new FormData(document.getElementById("ff")),
        url:"xxx",
        success:function(a){
              document.getElementById("img").src="/static/"+a
        },
        processData: false,#禁止编码请求参数
        contentType: false #不设置请求头
	   }
)
$.ajax({xhr:function(){
              var xhr = $.ajaxSettings.xhr();//获取当前的xhr
              xhr.upload.onprogress=function(p){
                  if(p.loaded==p.total)
                      console.log("上传完成")
              }
              return xhr;
	    }
        type:"post",
        data:new FormData(document.getElementById("ff")),
        url:"xxx",
        success:function(a){
              document.getElementById("img").src="/static/"+a
        },
        processData: false,#禁止编码请求参数
        contentType: false #不设置请求头
       }
)

实例

handler

import org.apache.commons.io.FilenameUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Oldman 2019/10/26 13:23
 * bug? 不存在的
 */
@Controller
public class UploadController {

    /**
     *
     * @param img   商品图片input框中的id
     * @param session
     * @return
     * @throws IOException
     */
    @PostMapping("ajaxupload")
    @ResponseBody
    public String ajaxUpload(MultipartFile img, HttpSession session) throws IOException {
        System.out.println("ajax上传");

        //获取文件的原始名称
        String filename = img.getOriginalFilename();
        //System.out.println("filename = " + filename);
        //定制全局唯一命名
        String unique = UUID.randomUUID().toString();
        //获取文件后缀
        String ext = FilenameUtils.getExtension(filename);
        //定制全局唯一文件名
        String uniqueFilename = unique + "." + ext;
        System.out.println("uniqueFilename = " + uniqueFilename);
        //获取存储目录的真实路径
        String real_path = session.getServletContext().getRealPath("/upload_img");

        String name = real_path + File.separator + uniqueFilename;
        //存储
        img.transferTo(new File(name));

        return uniqueFilename;
    }
}

前端(测试使用)

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>添加商品</h1>
    <form action="${pageContext.request.contextPath}/addgoods" method="post" enctype="multipart/form-data">
        商品名:<input type="text" name="goodsname">  <br>
        商品图片:<input type="file" name="img" >  <img height="21px" id="sig"/> <br>
        <input type="button" value="上传图片" onclick="upload()">  <br>
        图片预览:<img id="img" width="100px" height="100px">  <br>
        商品类型:<select name="goodsType">
                    <c:forEach items="${typeList}" var="type">
                        <option>${type.typeName}</option>
                    </c:forEach>
                </select>   <br>
        商品详情:<input type="text" name="detail">   <br>
        创建日期:<input type="date" name="createTime">   <br>
        <input type="submit" value="提交">  <br>
    </form>

    <script type="text/javascript">

        function upload() {
            //准备上传,显示进度条
            document.getElementById("sig").src="${pageContext.request.contextPath}/img/loading.gif";
            //$("#sig").attr("src","$ {pageContext.request.contextPath}/img/loading.gif");
            //创建xhr
            var xhr = new XMLHttpRequest();
            xhr.open("post","/ajaxupload");
            //设置监听:获取文件上传进度
            xhr.upload.onprogress=function (a) {  //文件上传过程中不断触发
                console.log(a.loaded);
                console.log(a.total);
                if (a.loaded == a.total) {
                    //$("#sig").attr("src", "$ {pageContext.request.contextPath}/img/ok.jpg")
                    document.getElementById("sig").src="${pageContext.request.contextPath}/img/ok.jpg";
                }
            };
            //设置监听,获取响应内容
            xhr.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    var ret = xhr.responseText;   //接收相应内容,图片在服务器中的位置(访问路径)
                    var res = ret.substr(1,ret.length-2);
                    //alert(res);
                    console.log(res)
                    //回显上传的图片
                    document.getElementById("img").src="${pageContext.request.contextPath}/upload_img/"+res;

                }
            }
            //FormData(form的dom对象)
            xhr.send(new FormData(document.forms[0]));
        }

    </script>

</body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值