HTML5页面
- <form id="uploadForm" enctype="multipart/form-data">
- <input id="file" type="file" name="file" multiple="multiple" onchange="selectFile()"/><br>
- form>
JS
//引入jquery
项目需要阿里巴巴的fastjson以便返回json数据
pom.xml
com.alibaba fastjson 1.2.59
后台代码
保存路径是
项目文件\target\classes\static\images\temp
@PostMapping("upload")
@ResponseBody
public JSONObject upload(@RequestParam("file") MultipartFile file){
JSONObject josn=new JSONObject();
try {
String pathA= ResourceUtils.getURL("classpath:").getPath()+"static";
String detail_path="/images/temp/";
if (file.isEmpty()){
josn.put("code","error");
josn.put("message","未选择文件");
return josn;
}
File fileA=new File(pathA);
if(!fileA.exists){
fileA.mkdirs();
}
String filename = file.getOriginalFilename(); //获取上传文件原来的名称
String filePath = pathA+detail_path;
System.out.println(filePath);
File temp = new File(filePath);
if (!temp.exists()){
temp.mkdirs();
}
File localFile = new File(filePath+filename);
file.transferTo(localFile); //把上传的文件保存至本地
System.out.println(file.getOriginalFilename()+" 上传成功");
josn.put("code","sucess");
//返回文件上传后的目录
josn.put("message",detail_path+filename);
return josn;
}catch (IOException e){
e.printStackTrace();
josn.put("code","error");
josn.put("message","文件上传失败,原因是:"+e.getMessage());
return josn;
}
}