文章詳情頁(yè)
基于Spring Boot利用 ajax實(shí)現(xiàn)上傳圖片功能
瀏覽:293日期:2022-06-11 17:53:44
效果如下:
1.啟動(dòng)類中加入
SpringBoot重寫addResourceHandlers映射文件路徑
@Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/E/"); }
設(shè)置靜態(tài)資源路徑
2. 表單 前端 頁(yè)面
<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)上傳圖片功能,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
標(biāo)簽:
Ajax
相關(guān)文章:
1. Terracotta for Spring 發(fā)布 -- 為Spring添加集群功能2. Spring Security整合Oauth2實(shí)現(xiàn)流程詳解3. springboot用controller跳轉(zhuǎn)html頁(yè)面的實(shí)現(xiàn)4. 如何解決Spring in action @valid驗(yàn)證不生效的問題5. Spring框架配置java web實(shí)現(xiàn)實(shí)例化6. Springboot 跨域配置無效及接口訪問報(bào)錯(cuò)的解決方法7. static關(guān)鍵字有何魔法?竟讓Spring Boot搞出那么多靜態(tài)內(nèi)部類(推薦)8. AspectJ領(lǐng)導(dǎo)人Adrian Colyer跳槽到Spring9. 解決spring data jpa 批量保存更新的問題10. Java 如何從spring容器中獲取注入的bean對(duì)象
排行榜
