springboot上传文件并返回url过程
明明joy 人气:2springboot上传文件并返回url
1.首先在yml中配置文件上传地址
2.文件保存本地没有配置在服务器上 需要多写一个api,在上传的最后生成一个url
直接上代码
@Slf4j @Service public class StuEmailPhotoServiceImpl implements StuEmailPhotoService { @Value("${file.email_img_url}") String imageUrl; @Value("${img.url}") String imgUrl; @Resource StuEmailPhotoMapper stuEmailPhotoMapper; /** * 邮件上传图片 * * @param classId * @param file * @param request * @return */ @Override public ResultImg batchUpload(Long classId, MultipartFile file, HttpServletRequest request) { if (null == file) { return new ResultImg(ResultInfo.FAIL_CODE, "传入文件为空!"); } String errMsg = null; String newName = null; try { String oldName = file.getOriginalFilename().toLowerCase(); //获取图片的名称 String imgPath = null; newName = classId + "-emailTemplate-" + UUID.randomUUID() + oldName.substring(oldName.lastIndexOf(".")); imgPath = imageUrl + classId; // + "/" + newName File folder = new File(imgPath); //没有文件夹就创建 if (!folder.exists()) { folder.mkdirs(); } //压缩图片再保存outputQuality(1f) 越接近1,图片质量越高 String suffix = oldName.substring(oldName.lastIndexOf(".") + 1); Thumbnails.of(file.getInputStream()).scale(1f).outputQuality(1f).outputFormat(suffix).toFile(new File(folder, newName)); //存储图片信息 StuEmailPhoto stuEmailPhoto = new StuEmailPhoto(); stuEmailPhoto.setClassId(classId); stuEmailPhoto.setImgOname(oldName); stuEmailPhoto.setImgName(newName); stuEmailPhoto.setImgUrl(imgPath + "/" + newName); stuEmailPhoto.setCreateTime(DateFormatUtils.getCurrentTime()); stuEmailPhoto.setCreator(SecurityUtils.getCurrentUserId()); stuEmailPhotoMapper.insert(stuEmailPhoto); } catch (Exception e) { errMsg = e.getLocalizedMessage(); log.error("------StuPlatTrans--------batchUpload-----------:" + e); } if (StringUtils.isNotEmpty(errMsg)) { return new ResultImg(ResultInfo.FAIL_CODE, errMsg); } String url = imgUrl + "api/selectData/readImageView/emailTemplate/" + classId + "/" + newName; ImgUrl imgUrl = new ImgUrl(); imgUrl.setUrl(url); List<ImgUrl> urlList = new ArrayList(); urlList.add(imgUrl); return new ResultImg(0, urlList); } /** * 浏览器读取图片 * * @param classId * @param imgName * @param request * @param response */ @Override public void readImageView(Long classId, String imgName, HttpServletRequest request, HttpServletResponse response) { log.info("----------调用邮箱readImageView方法---------------"); ServletOutputStream outputStream = null; FileInputStream inputStream = null; try { //获取图片存放路径 String imgPath = null; StuEmailPhoto stuEmailPhoto = stuEmailPhotoMapper.getUrlByNameAndClassId(classId, imgName); imgName = stuEmailPhoto.getImgName(); String suffix = imgName.substring(imgName.lastIndexOf(".") + 1); // StuPlatTransfer transfer = transferMapper.getImageUrlByName(java.net.URLDecoder.decode(imgName, "utf-8") ); log.info(JsonHelper.toJsonString(stuEmailPhoto)); imgPath = stuEmailPhoto.getImgUrl(); if (null != imgPath) { File imgFile = new File(imgPath); if (!imgFile.exists()) { return; } // response.setContentType("application/octet-stream; charset=utf-8"); response.addHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); response.addHeader("Access-Control-Expose-Headers", "token,uid,Content-Disposition"); response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE"); response.addHeader("Access-Control-Allow-Headers", "Content-Type"); response.addHeader("Access-Control-Allow-Credentials", "true"); response.addHeader("Content-Length", "" + imgFile.length()); response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); inputStream = new FileInputStream(imgFile); response.setContentType("image/" + suffix + ";charset=utf-8"); outputStream = response.getOutputStream(); //读取文件流 int len = 0; byte[] buffer = new byte[1024 * 10]; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.flush(); } } catch (Exception e) { log.error("-----readImageView---imageName--" + imgName + "--err:" + e); } finally { try { if (outputStream != null) { outputStream.close(); } } catch (IOException e) { log.error("-----readImageView---input close--" + imgName + "--e:" + e); } try { if (inputStream != null) { inputStream.close(); } } catch (IOException e) { log.error("-----readImageView---out close--" + imgName + "--e:" + e); } } } }
springboot上传文件两种方式
1.文件保存在服务器,url地址保存在数据库
/** * 1.文件保存在服务器,url地址保存在数据库 * 上传成功之后返回成功保存的url地址 */ @PostMapping("/upload") public @ResponseBody String upload(@RequestParam MultipartFile file, HttpServletRequest request){ if(!file.isEmpty()){ String uploadPath = "C:\uploadFile"; // 如果目录不存在则创建 File uploadDir = new File(uploadPath); if (!uploadDir.exists()) { uploadDir.mkdir(); } String OriginalFilename = file.getOriginalFilename();//获取原文件名 String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取文件后缀名 //重新随机生成名字 String filename = UUID.randomUUID().toString() +suffixName; File localFile = new File(uploadPath+"\"+filename); try { file.transferTo(localFile); //把上传的文件保存至本地 /** * 这里应该把filename保存到数据库,供前端访问时使用 */ return filename;//上传成功,返回保存的文件地址 }catch (IOException e){ e.printStackTrace(); System.out.println("上传失败"); return ""; } }else{ System.out.println("文件为空"); return ""; } }
2.直接把文件以二进制形式保存到数据库中数据类型为blob的一个字段
/** *上传图片,使用mybatis-plus保存到数据库 *User为实体类,数据库对应user表,有id、image两个属性 */ @PostMapping("/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) throws Exception{ if(!file.isEmpty()){ User user=new User(); user.setImage(file.getBytes()); userMapper.insert(user); } return "ok"; } /** *前端通过id获取数据库中的图片 */ @GetMapping("/getImage") @ResponseBody public void getImage(String id,HttpServletResponse resp) throws Exception{ User user=userMapper.selectById(id); byte[] image = (byte[])user.getImage(); resp.setContentType("image/jpeg"); ServletOutputStream out = resp.getOutputStream(); out.write(image); out.flush(); out.close(); }
3.前端代码
<form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /><br/> <input type="submit" name="" id="" value="提交" /> </form>
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。
加载全部内容