基于Spring Boot利用 ajax實(shí)現(xiàn)上傳圖片功能
效果如下:


1.啟動(dòng)類中加入

SpringBoot重寫addResourceHandlers映射文件路徑
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/E/");
}
設(shè)置靜態(tài)資源路徑
2. 表單 前端 頁面
<input type="file" name="file" id="file">
<p id="url"><img src="" width=200></p>
<input type="button" id="button" value="上傳" >
$(function () {
$("#button").click(function () {
var form = new FormData();
form.append("file", document.getElementById("file").files[0]);
$.ajax({
url: "/stu/upload", //后臺(tái)url
data: form,
cache: false,
async: false,
type: "POST", //類型,POST或者GET
dataType: 'json', //數(shù)據(jù)返回類型,可以是xml、json等
processData: false,
contentType: false,
success: function (data) { //成功,回調(diào)函數(shù)
if (data) {
var pic="/imctemp-rainy/"+data.fileName;
$("#url img").attr("src",pic);
// alert(JSON.stringify(data));
} else {
alert("失敗");
}
},
error: function (er) { //失敗,回調(diào)函數(shù)
alert(JSON.stringify(data));
}
});
})
})
控制器
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();
}
//處理文件上傳
@ResponseBody //返回json數(shù)據(jù)
@RequestMapping(value = "upload", method = RequestMethod.POST)
public JSONObject uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
String contentType = file.getContentType();
System.out.print(contentType);
String fileName = System.currentTimeMillis()+file.getOriginalFilename();
String filePath = "D:/E";
JSONObject jo = new JSONObject();//實(shí)例化json數(shù)據(jù)
if (file.isEmpty()) {
jo.put("success", 0);
jo.put("fileName", "");
}
try {
uploadFile(file.getBytes(), filePath, fileName);
jo.put("success", 1);
jo.put("fileName", fileName);
// jo.put("xfileName", filePath+"/"+fileName);
} catch (Exception e) {
// TODO: handle exception
}
//返回json
return jo;
}
總結(jié)
以上所述是小編給大家介紹的基于Spring Boot利用 ajax實(shí)現(xiàn)上傳圖片功能,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
AJAX實(shí)現(xiàn)web頁面中級(jí)聯(lián)菜單的設(shè)計(jì)
Ajax 無刷新在注冊用戶名時(shí)的應(yīng)用的代碼
用ajax xml的數(shù)據(jù)讀取的HelloWorld程序
自己動(dòng)手打造ajax圖片上傳(網(wǎng)上沒有的)
ajax+springmvc實(shí)現(xiàn)C與View之間的數(shù)據(jù)交流方法
利用AJAX實(shí)現(xiàn)鼠標(biāo)懸浮獲取值的代碼
利用AjaxSubmit()方法實(shí)現(xiàn)Form提交表單后回調(diào)功能
不使用XMLHttpRequest對象實(shí)現(xiàn)Ajax效果的方法小結(jié)

