上传照片
//上传图片1
function upload() {
var formData = new FormData();
var name = $("#pic").val();
formData.append("myfiles",$("#pic")[0].files[0]);
formData.append("name",name);
$.ajax({
url : "/upload.json",
type : 'POST',
data : formData,
// 告诉jQuery不要去处理发送的数据
processData : false,
// 告诉jQuery不要去设置Content-Type请求头
contentType : false,
beforeSend:function(){
console.log("正在进行,请稍候");
},
success : function(data) {
console.log(data);
$("#imgBusy").attr("src",data.url);
$("#inBusy").val(data.url);
if(data.result==0){
console.log("成功"+data);
}else{
console.log("失败");
}
},
error : function(responseStr) {
console.log("error");
},
});
}
//上传图片
@RequestMapping(value = "/upload.json", method = RequestMethod.POST)
public @ResponseBody Map
upload(@RequestParam MultipartFile myfiles,HttpServletRequest request) throws IOException {
if(myfiles.isEmpty()){
System.out.println("文件未上传");
}
System.out.println("文件长度: " + myfiles.getSize());
System.out.println("文件类型: " + myfiles.getContentType());
System.out.println("文件名称: " + myfiles.getName());
System.out.println("文件原名: " + myfiles.getOriginalFilename());
System.out.println("========================================");
//如果用的是Tomcat服务器,则文件会上传到\%TOMCAT_HOME%\webapps\YourWebProject\WEB-INF\upload\文件夹中
String realPath = request.getSession().getServletContext().getRealPath("/view/uploadfile");
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉,我是看它的源码才知道的
String fileName = myfiles.getOriginalFilename();
String newFileName = UUID.randomUUID().toString().replaceAll("-", "")+"."+FilenameUtils.getExtension(fileName);
FileUtils.copyInputStreamToFile(myfiles.getInputStream(), new File(realPath,newFileName));
// String host = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort();
Map map = new HashMap();
map.put("result",0);
map.put("url", "/view/uploadfile/"+newFileName);
return map;
}