前端js代码:
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");
}
}