<input type="file" id="file"><br/> <button class="btn btn-danger" id="btn_upload_excel"> 上传</button>
$("#btn_upload_excel").click(function () { var fileObj =document.getElementById('file').files; // js 获取文件对象 if (typeof (fileObj) == "undefined" || fileObj.size <= 0) { alert("请选择文件"); return; } var formFile = new FormData(); //formFile.append("action", "emp/import"); formFile.append("excel_file", fileObj[0]); //加入文件对象 var data = formFile; $.ajax({ url: "emp/import", data: data, type: "Post", dataType: "json", cache: false,//上传文件无需缓存 processData: false,//用于对data参数进行序列化处理 这里必须false contentType: false, //必须 success: function (result) { alert("上传完成!"); }, }) })
java后台: @RequestMapping(value = "/emp/import", method = RequestMethod.POST) public void importExcel(@RequestParam("excel_file") MultipartFile files, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = null; String tempPath=null; try { fileName = files.getOriginalFilename(); byte[] bytes = files.getBytes(); String savePath = request.getServletContext().getRealPath("/WEB-INF/upload"); //上传时生成的临时文件保存目录 tempPath = request.getServletContext().getRealPath("/WEB-INF/temp"); File tmpFile = new File(tempPath); if (!tmpFile.exists()) { //创建临时目录 tmpFile.mkdir(); } BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(new File(tempPath + fileName))); buffStream.write(bytes); buffStream.close(); } catch (Exception e) { throw new Exception( "You failed to upload " + fileName + ": " + e.getMessage()); } }