<div class="col-md-4">
<img id="imgBusy" src="images/icon_img.png" class="zf-pic"/>
<input type="hidden" id="inBusy" value=""/>
</div>
<span class="addPic col-md-2">web
<input type="file" id="pic" onchange="upload()"/>上傳照片</span>ajax
//上傳圖片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");
},
});
}json
//上傳圖片
@RequestMapping(value = "/upload.json", method = RequestMethod.POST)
public @ResponseBody Map<String, Object> 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<String,Object> map = new HashMap();
map.put("result",0);
map.put("url", "/view/uploadfile/"+newFileName);
return map;
}服務器