传统文件上传
-
导入jar包:commons-fileupload, commons-io
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
在前端提供一个form表单和文件选择域
-
编写controller
@RequestMapping("/fileupload") public String fileupload(HttpServletRequest request){ //上传的位置(上传后保存的位置) String path = request.getSession().getServletContext().getRealPath("/uploads"); File file = new File(path); if(!file.exists()){ //如果路径不存在 file.mkdirs(); //创建文件夹 } //解析request对象,获取上传文件项 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //解析request List<FileItem> items = upload.parseRequest(request); for(FileItem item: items){ if(item.isFormFiled){ //如果是普通表单项 //TODO }else{ //如果是上传文件项 String filename = item.getName(); //获取上传文件的名称 //可选:设置名称为唯一值 String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid+"_"+filename; item.write(new File(path, filename)); //完成文件上传 item.delete(); //删除临时文件(清理垃圾) } } }
-
注意事项
form表彰的enctype取值必须是:multipart/form-data(用分隔符将表彰内容分隔成多个部分),默认为application/x-www-form-urlencoded(普通键值对的形式)
method属性值为Post
SpringMVC 上传文件
-
配置文件解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <property name="maxUploadSize" value="10*1024*1024" /> </bean>
在前端提供一个form表单和文件选择域(name值与controller的文件参数保持一致)
-
编写controller
@RequestMapping("/fileupload") public String fileupload(HttpServletRequest request, MultipartFile upload) throws Exception{ //上传的位置(上传后保存的位置) String path = request.getSession().getServletContext().getRealPath("/uploads"); File file = new File(path); if(!file.exists()){ //如果路径不存在 file.mkdirs(); //创建文件夹 } String filename = upload.getOriginalFilename(); //获取上传文件的名称 //可选:设置名称为唯一值 String uuid = UUID.randomUUID().toString().replace("-", ""); filename = uuid+"_"+filename; upload.transferTo(new File(path, filename)); //完成文件上传,不用删除临时文件 }
Ajax上传,Springboot接收
-
html
<form> <input type="file" name="upload" id="upload"/> <br/> <span id="submited" onclick="uploadFile()">上传</span> </form>
-
js(使用FormData存放表单数据)
function uploadFile() { var files = document.getElementById("upload").files; var formdata = new FormData(); formdata.append("upload",files[0]); $.ajax({ url:"/testUpload", type:"post", data:formdata, contentType:false, //- 必须false才会自动加上正确的Content-Type processData: false, //- 必须false才会避开jQuery对 formdata 的默认处理,XMLHttpRequest会对 formdata 进行正确的处理 success:function(){ alert("success"); }, error:function(){ alert("error"); } }); }
-
Springboot Controller
@RequestMapping("/testUpload") @ResponseBody public String testUpload(@RequestParam("upload") MultipartFile upload){ System.out.println(upload.getOriginalFilename()); return ""; }
加载本地资源并返回给页面
-
Springboot
@RequestMapping("/imgurl") @ResponseBody public String createFolw(HttpServletResponse response) { // response.setContentType("image/*"); FileInputStream fis = null; OutputStream os = null; try { fis = new FileInputStream("D:/wechat.jpg"); os = response.getOutputStream(); int count = 0; byte[] buffer = new byte[1024 * 8]; while ((count = fis.read(buffer)) != -1) { os.write(buffer, 0, count); os.flush(); } } catch (Exception e) { e.printStackTrace(); } try { fis.close(); os.close(); } catch (IOException e) { e.printStackTrace(); } return "ok"; }