关于文件上传的记录:
1:自定义file文件样式:
<input type=file id=browsefile style=“visibility:hidden” οnchange=filepath.value=this.value>
2。选择图片上,将图片写入到指定目录,传路径到数据库。
出于个人习惯 前段采用angularjs
$scope.uploadFile=function(){
EmpService.uploadFile().success(
function(response){
if(response.flag){
alert(response.message);
}
else{
alert(response.message);
}
});
}
this.uploadFile = function(){
// 向后台传递数据:
var formData = new FormData();
// 向formData中添加数据:
formData.append("file",file.files[0]);
return $http({
method:'post',
url:'../emp/uploadFile.do',
data:formData,
headers:{'Content-Type':undefined} ,// Content-Type : text/html text/plain
transformRequest: angular.identity
});
}
```angular默认采用json格式传输,因此此处必须设置undefined
``` 前端不用多说了,主要看后台:
@RequestMapping("/uploadFile")
public Result fileUpload(MultipartFile file) throws Exception, IOException{
//示例图片上传
String fileName=file.getOriginalFilename();
//修改唯一文件名
int endIndex=fileName.lastIndexOf('.');
String newFileName=UUID.randomUUID().toString()+fileName.substring(0, endIndex);
String end=fileName.substring(endIndex);
//指定文件上传目录
File filePath=new File("E:/upload/img/"+newFileName+end);
System.out.println(filePath);
//如果文件夹不存在,则创建文件夹
if(!filePath.exists())
{
filePath.mkdir();
}
//写如磁盘
file.transferTo(filePath);
//将文件路径存到数据库
String empImg="E:/upload/img"+newFileName+end;
empService.uploadFile(empImg);
return new Result(true, "ok");
}
注意:这里的**MultipartFile file** 得和AjAx里面的formData.append("file",file.files[0]);字段对应。