package com.lzh.controller; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import java.util.UUID; import javax.servlet.http.HttpSession; import org.springframework.stereotype.Controller; import org.springframework.util.Base64Utils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; @Controller @RequestMapping("/upload") public class AjaxUpload { @RequestMapping("/img") @ResponseBody public String uploadImg(@RequestParam("image") String imgStr, HttpSession session) { String filePath = null; String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase(); filePath = session.getServletContext().getRealPath("/upload"); //不存在就创建 File file = new File(filePath); if (!file.exists() && !file.isDirectory()) { System.out.println("文件夹不存在"); file.mkdir(); } filePath = filePath + "\\" + uuid + ".jpg"; try { //俩种方式解密Base64 后者更简单 /* // Base64 byte[] b; b = decoder.decodeBuffer(imgStr.split(",")[1]); for (int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } */ //因为BASE64Decoder的jar问题,此处使用spring框架提供的工具包 byte[] b = Base64Utils.decodeFromString(imgStr.split(",")[1]); System.out.println(filePath); OutputStream out = new FileOutputStream(filePath); out.write(b); out.flush(); out.close(); } catch (Exception e) { String json = "{\"result\":\"服务器异常\"}"; return json; } String imgePath = "upload/" + uuid + ".jpg"; String json = "{\"result\":\"ok\",\"file\":\""+imgePath+"\"}"; System.out.println(json); return json; } }


tianli3000 LV8
2022年2月24日
czr2233 LV9
2021年9月14日
1964867825
2021年9月6日
暂无贡献等级
天天 LV9
2021年9月4日
xiaoxiexie LV13
2021年4月26日
fantesy LV17
2021年4月7日
stellafull LV2
2021年1月17日
helloworldsbsb LV7
2020年12月28日
mengxiaoyao LV3
2020年8月4日
dl51918 LV3
2020年6月23日