前端js代碼:html
function fileSubmit() { var formData = new FormData(); formData.append("file",$("#FileUpload")[0].files[0]); var type = $('#file_type').val() var user = $('#file_user').val() formData.append("type",type) formData.append("user",user) $.ajax({ url: baseURL+"etl/upload", data: formData, type: "Post", dataType: "formData", cache: false,//上傳文件無需緩存 processData: false,//用於對data參數進行序列化處理 這裏必須false contentType: false, //必須 success: function (data) { console.log(data) console.log("success") if(data.code == 500){ console.log(data.msg) console.info("error"); $('#file_sqlRes').html("<span>"+data.msg+"</span>") }else{ var taskId = data.taskId $('#file_sqlRes').html("<span>TaskId爲:"+taskId+"</span>") } }, error: function (data) { } }) }
後端Java代碼:前端
/** * 單文件上傳 * * @param file */ @RequestMapping(value = "/upload", method = RequestMethod.POST) @ResponseBody public AjaxObject upload(@RequestParam("file") MultipartFile file,String type,Long user) { String taskType = "F"; String featureType = type; Long userOpt = user; Long taskId = etlUtil.getTaskId(); if (file.isEmpty()) { return AjaxObject.error(500, "上傳文件失敗,請檢查上傳的文件"); } // 獲取文件名 String fileName = file.getOriginalFilename(); logger.info("上傳的文件名爲:" + fileName); // 獲取文件的後綴名 String suffixName = fileName.substring(fileName.lastIndexOf(".")); logger.info("上傳的後綴名爲:" + suffixName); // 文件上傳後的路徑 String filePath = etlConf.getUploadFilePath(); File dest = new File(filePath + fileName); // 檢測是否存在目錄 if (!dest.getParentFile().exists()) { dest.getParentFile().mkdirs(); } try { file.transferTo(dest); Long res = 123L if (res != 0) { etlUtil.runDatax(taskId.toString(), featureType); logger.info("taskId", taskId.toString()); return AjaxObject.ok().put("taskId", taskId.toString()); } else { logger.error("TaskId插入失敗"); return AjaxObject.error(500, "TaskId插入失敗,請聯繫管理員!").put("taskId", taskId.toString()); } } catch (IllegalStateException e) { e.printStackTrace(); logger.error(e.toString(),e); return AjaxObject.error(500, "上傳文件失敗,請檢查上傳的文件,IllegalStateException"); } catch (IOException e) { e.printStackTrace(); logger.error(e.toString(),e); return AjaxObject.error(500, "上傳文件失敗,請檢查上傳的文件,IOException"); } }