package com.izouma.walkchina.web; import com.izouma.walkchina.domain.Result; import com.izouma.walkchina.service.storage.StorageService; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.RandomStringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.util.Base64Utils; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.*; import java.net.URI; import java.net.URLConnection; import java.text.SimpleDateFormat; import java.util.Base64; import java.util.Date; @RestController @RequestMapping("/upload") @Slf4j public class FileUploadController { @Autowired private StorageService storageService; @PostMapping("/file") public Result uploadFile(@RequestParam("file") MultipartFile file, @RequestParam(value = "path", required = false) String path) { if (path == null) { String basePath = "application"; try { basePath = file.getContentType().split("/")[0]; } catch (Exception ignored) { } path = basePath + "/" + new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()) + RandomStringUtils.randomAlphabetic(8) + "." + FilenameUtils.getExtension(file.getOriginalFilename()); } InputStream is; try { is = file.getInputStream(); } catch (IOException e) { log.error("上传失败", e); return Result.error("上传失败"); } String result = storageService.uploadFromInputStream(is, path); return Result.ok(result); } @PostMapping("/base64") public Result uploadImage(@RequestParam("base64") String base64, @RequestParam(value = "path", required = false) String path) { base64 = base64.substring(base64.indexOf(',') + 1); Base64.Decoder decoder = Base64.getDecoder(); if (path == null) { String ext = ".jpg"; try { InputStream is = new ByteArrayInputStream(decoder.decode(base64.getBytes())); String type = URLConnection.guessContentTypeFromStream(is); ext = type.replace("image/", ".").replace("jpeg", "jpg"); } catch (Exception ignored) { } path = "image/" + new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss").format(new Date()) + RandomStringUtils.randomAlphabetic(8) + ext; } InputStream is; try { is = new ByteArrayInputStream(decoder.decode(base64.getBytes())); } catch (Exception e) { log.error("上传失败", e); return Result.error("上传失败"); } String result = storageService.uploadFromInputStream(is, path); return Result.ok(result); } }