ajax(form)图片上传(spring)
第一步:spring-web.xml
<!--配置上传下载--> <bean id="multipartResolver" class="org.springframework.web.multipart.support.StandardServletMultipartResolver" />
第二步:后台
@RequestMapping(value = "/bbbbb", method = RequestMethod.POST) public String imageshangchuan(@RequestPart("xxx") MultipartFile multipartFile, Model model, HttpServletRequest request) { if (!multipartFile.getContentType().contains("image/")) { model.addAttribute("err", "只能是图片文件!"); return "/inputfile"; } if (multipartFile.getSize() > 1024 * 1024 * 5) { model.addAttribute("err", "只能是5M以下!"); return "/inputfile"; } //取得相对路径 String basePath = request.getServletContext().getRealPath("/img"); String rekativePath; try { rekativePath = makeImagePath(basePath, multipartFile.getOriginalFilename()); File file = new File(rekativePath); file.getParentFile().mkdir(); multipartFile.transferTo(file); } catch (IOException e) { model.addAttribute("err", "上传失败,请重试"); return "/inputfile"; } return "/index"; } public String makeImagePath (String basePath, String fileName){ Date date = new Date(); String[] filename = simpleFile(fileName); return String.format("%s%s%s%supload_%s_%s.%s", basePath, File.separator, new SimpleDateFormat("yyyyMMdd").format(date), File.separator, filename[0], new SimpleDateFormat("hhmmss").format(date), filename[1] ); } public String[] simpleFile (String file){ int sum = file.lastIndexOf("."); return new String[]{ file.substring(0, sum), file.substring(sum + 1) }; }
第三步:web.xml
<multipart-config> <max-file-size>102400</max-file-size> </multipart-config>
第四步:jsp
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form:form action="/bbbbb" method="post" enctype="multipart/form-data"> <div style="color: red"> ${err} </div> <input type="file" name="xxx" /> <input type="submit"/> </form:form> </body> </html>
运行测试
使用ajax
js
function asdsa() { var formData = new FormData(); formData.append("xxx",document.getElementById("myfile").files[0]); $.ajax({ url: '/bbbbb', type: 'POST', Accept: 'text/html;charset=UTF-8', cache: false, contentType:false, data:formData, processData: false, xhr: function () { myXhr = $.ajaxSettings.xhr(); console.log(myXhr.upload); if (myXhr.upload) { myXhr.upload.addEventListener('progress', function (e) { console.log(e); var loaded = e.loaded;//已经上传大小情况 var tot = e.total;//附件总大小 var per = Math.floor(100 * loaded / tot); //已经上传的百分比 console.log('附件总大小 = ' + loaded); console.log('已经上传大小 = ' + tot); }, false); } return myXhr; }, success: function (data) { console.log(data); console.log("上传成功!!!!"); }, error: function () { console.log("上传失败!"); } }); }
jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/11/6 Time: 20:00 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <script src="css/jquery-1.11.3.js"></script> <script> $(function () { $.get("login.html", {name: "John", time: "2pm"}, function (data) { console.log(data); }); }) </script> <body> <h1>测试</h1> <button onclick="asdsa()">测试</button> <meter id="p1" value="60" max="100">60%</meter> <input id="myfile" type="file" multiple="multiple"/> <progress id='progress' style='width:100px' value='0' max='100'>3/10</progress> <audio controls="controls" src="mp3/白小白%20-%20最美情侣.mp3"/> <img id="imd" src=""/> <script> function asdsa() { var formData = new FormData(); formData.append("xxx",document.getElementById("myfile").files[0]); $.ajax({ url: '/bbbbb', type: 'POST', Accept: 'text/html;charset=UTF-8', cache: false, contentType:false, data:formData, processData: false, xhr: function () { myXhr = $.ajaxSettings.xhr(); console.log(myXhr.upload); if (myXhr.upload) { myXhr.upload.addEventListener('progress', function (e) { console.log(e); var loaded = e.loaded;//已经上传大小情况 var tot = e.total;//附件总大小 var per = Math.floor(100 * loaded / tot); //已经上传的百分比 console.log('附件总大小 = ' + loaded); console.log('已经上传大小 = ' + tot); }, false); } return myXhr; }, success: function (data) { console.log(data); console.log("上传成功!!!!"); }, error: function () { console.log("上传失败!"); } }); } function da() { var files = document.getElementById("myfile").files[0]; var read = new FileReader(); read.readAsDataURL(files); read.onprogress = function (ev) { } read.onload = function (ev) { var c = document.getElementById("p1"); c.value = 100; progress.value = 50; var c = document.getElementById("imd"); c.src = ev.target.result; progress.value = 100; } ; } </script> </body> </html>