文章詳情頁
基于Spring Boot利用 ajax實(shí)現(xiàn)上傳圖片功能
瀏覽:184日期: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. 表單 前端 頁面
<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", //后臺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)載,煩請注明出處,謝謝!
標(biāo)簽:
Ajax
相關(guān)文章:
1. 多個(gè)SpringBoot項(xiàng)目采用redis實(shí)現(xiàn)Session共享功能2. Spring Framework 1.2.6 發(fā)布3. 使用springboot aop來實(shí)現(xiàn)讀寫分離和事物配置4. Springboot和bootstrap實(shí)現(xiàn)shiro權(quán)限控制配置過程5. Spring Utils工具類常用方法實(shí)例6. SpringBoot+SpringCache實(shí)現(xiàn)兩級緩存(Redis+Caffeine)7. springboot基于Redis發(fā)布訂閱集群下WebSocket的解決方案8. Spring Cache和EhCache實(shí)現(xiàn)緩存管理方式9. SpringBoot+SpringSession+Redis實(shí)現(xiàn)session共享及唯一登錄示例10. Spring基于注解讀取外部配置文件
排行榜
