前端代码不展示,通过ajax请求后台地址,完成上传文件
//文件上传
public static 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();
}
//处理文件上传
@Log("文件上传")
@RequestMapping(value = "uploadImg", method = RequestMethod.POST)
public R uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws JSONException {
String contentType = file.getContentType();
System.out.println(contentType);
String fileName = System.currentTimeMillis()+file.getOriginalFilename(); //随机生成文件名
System.out.println(fileName);
int code=0;
String filePath = "D:img"; //上传到本地的路径,D盘下的img文件夹
if (file.isEmpty()) {
code=1;
fileName="";
}
try {
uploadFile(file.getBytes(), filePath, fileName);
code=0;
} catch (Exception e) {
// TODO: handle exception
}
//返回json
return R.ok().put("code", code).put("fileName", "/imctemp-rainy/"+fileName); //处理成功返回的结果,
data.code=0 //表示上传成功
data.fileName //返回上传的文件名,例:/imctemp-rainy/+文件名
}