电脑
intellij IDEA或者eclipse
第一种:创建一个springboot的项目。1、 打开创建页面 选择File-new-project..2、选择创建的项目为spring initializr 进入springboot项目创建步骤(也可以选择类型java,创建一个普通java项目)3、输入项目名字,选择依赖web(根据项目需求选择,此次需要),选择存放目录-完成(Finish)4、在pom.xml中引入html以依赖
第二种:创建一个简单的javaweb项目。1、创建一个基本的javaweb项目2、集成springmvc开发环境
第一步:实现思路。1、借助于springboot的框架(springboot集成springmvc),实现上传的后天功能。将文件上传到D:\img下2、前端借助于原生js实现对上传请求的监控获得上传进度,请求完成的情况下
第二步:编写controllerimport org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import javax.servlet.http.HttpServletRequest;import java.io.File;import java.io.FileOutputStream;//访问地址:http://localhost:8080/toAsyn@Controllerpublic class UploadController { // 跳转到上传文件的页面 @RequestMapping(value = '/toAsyn', method = RequestMethod.GET) public String toAsyn() { // 跳转到 templates 目录下的 uploadimg.html return 'asyn'; } // 处理文件上传 @ResponseBody @RequestMapping(value = '/testuploadimg', method = RequestMethod.POST) public String uploadImg(@RequestParam('file') MultipartFile file, HttpServletRequest request) { String contentType = file.getContentType(); String fileName = file.getOriginalFilename(); String filePath = 'd:/img/'; if (file.isEmpty()) { return '文件为空!'; } try { uploadFile(file.getBytes(), filePath, fileName); } catch (Exception e) { // TODO: handle exception } // 返回json return 'succes'; } private void uploadFile(byte[] file, String filePath, String fileName) throws Exception { File targetFile = new File(filePath); if (!targetFile.exists()) { targetFile.mkdirs(); } FileOutputStream out = new FileOutputStream(filePath + fileName); out.write(file); out.flush(); out.close(); }}
第三步:设置文件最大上传限制。1、新建application.yml放到前项目下的:src\main\resources\application.yml2、添加内容:spring: servlet: multipart: max-file-size: 120MB max-request-size: 120MB3:否则上传文件超过10485760 字节就会报错the request was rejected because its size (64050422) exceeds the configured maximum (10485760)
第四步:编写前端代码。1、路径在 当前项目的:src\main\resources\asyn.html
0% | ||
| ||
completed |
第一步:测试。1、为了测试上传进度效果此次测试文件大小为61MB2、启动服务进入:http://localhost:8080/toAsyn3、选择文件上传,测试成功,如下所示:
第二步:总结。1、非IE一般使用XMLHttpRequest,IE使用ActiveXObjectvar xmlHttp = null; //如果支持XMLHttpRequest则使用 if (XMLHttpRequest) { xmlHttp = new XMLHttpRequest(); } else { //如果是IE浏览器则需要使用 xmlHttp = new ActiveXObject('Microsoft.XMLHTTP'); }2、IE并不支持FormData对象var formData = new FormData();3、如果需要兼容ie需要解决以上两个问题
开发环境 jdk 1.8 IDEA 2018.2.2 maven:apache-maven-3.5.4
此次测试使用的guge浏览器,功能不兼容aiyi浏览器