AJAX异步上传文件

mac2023-01-24  57

一、ajax异步上传 :

 

1、通过jquery提供的方法$.ajax()完成上传

定义form表单:

<form method="post" enctype="multipart/form-data"> 商品id:<input type="text" name="id" value="${goods.id}" readonly="readonly"/></br> 商品名称:<input type="text" name="name" value="${goods.name}"/></br> 商品价格:<input type="text" name="price" value="${goods.price}"/> 商品类型:<select name="typeId" > <option value="1">新鲜水果</option> <option value="2">海鲜水产</option> <option value="3">猪牛羊肉</option> <option value="4">禽类蛋品</option> <option value="5">新鲜蔬菜</option> <option value="6">速冻食品</option> </select></br> 商品详情:<input type="text" name="detail" value="${goods.detail}" style="width: 350px; height: 30px ;"/></br> 上传图片:<input type="file" name="source"/></br> <img id="img"> <%--用于图片回显--%> <input type="button" value="修改" id="file01"/></br> </form>

定义ajax异步上传逻辑:

<script type="text/javascript"> $("#file01").click(function () { $.ajax({ url:"${pageContext.request.contextPath}/updateGoods", type:"POST", data:new FormData(document.forms[0]), //发送请求,携带form的所有数据 success:function (ret) { if (ret!=null){ alert("修改成功~") } // 回显上传图片 document.getElementById("img").src="upload/"+ret; }, processData:false, //禁止编码请求参数 contentType:false // 不设置请求头 }) }) </script>

2、原生ajax上传:

form表单提交按钮定义:

<input type="button" value="修改" onclick="update()"/> function upload(){ //准备上传:显示进度条 document.getElementById("sig").src="/static/app_ajax/load.gif"; //创建xhr xhr = new XMLHttpRequest(); xhr.open("post","${pageContext.request.contextPath}/updateGoods"); //设置监听:获取文件上传进度 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="upload/"+ret } } //FomrData(form的dom对象) xhr.send(new FormData(document.forms[0])) //发送请求,携带form的所有数据 }

 

后台接受参数:

@RequestMapping("/updateGoods") @RequiresAuthentication public String updateGoods(Goods goods, MultipartFile source, HttpServletRequest request, HttpServletResponse response) throws IOException { // 通过id 修改商品 System.out.println(goods); System.out.println(source); // 获取文件名称 String fileName = source.getOriginalFilename(); System.out.println(fileName); // 定义全局唯一标识 String uuid = UUID.randomUUID().toString(); // sing一全局唯一文件名 String uniqueName=uuid+fileName; System.out.println(uniqueName); // 获取磁盘路径 String realPath = request.getServletContext().getRealPath("/upload"); System.out.println(realPath); //文件存储路径 String path=realPath+"/"+uniqueName; String imgpath="upload"+"/"+uniqueName; System.out.println(imgpath); //将上传的文件存储到磁盘中 source.transferTo(new File(path)); // 修改 goods.setImgpath(imgpath); goods.setCreatTime(new Date()); goodsService.updateGoodsById(goods); response.getWriter().write(uniqueName); return null; }

 

 

 

 

 

 

 

最新回复(0)