springboot上传下载图片

该博客主要介绍了如何在Java中实现文件上传和下载服务。文件上传服务首先校验文件类型,仅允许特定格式的图片上传,然后使用UUID生成唯一文件名,并保存到指定路径。文件下载服务则根据URL读取文件并设置响应头,使浏览器能够下载文件。同时,提供了获取Tomcat的webapps路径和获取本地IP地址的方法。
摘要由CSDN通过智能技术生成

@Service
@Slf4j
public class FileUploadService {
@Resource
private Environment environment;
//获取文件存储路径
@Value("${upload.root.path}")
private String upfilePath;

//获取图片类型
@Value("${upload.pic.type}")
private String picTypes;

public ReturnObject<Object> picUpload(MultipartFile file, String upLoadPath) {
    String staticPath = environment.getProperty("spring.mvc.static-path-pattern");//img/**
    String url = environment.getProperty("ai.domain") + "/" + staticPath.split("/")[1] + "/" + upLoadPath;
    String originalFilename = file.getOriginalFilename();
    log.info("原始文件名:" + originalFilename);
    assert originalFilename != null;
    String format = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
    if (Arrays.asList(picTypes.split(",")).contains(format.toLowerCase())) {
        String videoName = UUID.randomUUID().toString();
        log.info("UUID文件名:" + videoName);
        String dateOne = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd/"));//todo
        String filePath;
        if (StringUtils.endsWith("/", upfilePath)) filePath = upfilePath + upLoadPath + dateOne;
        else filePath = upfilePath + "/" + upLoadPath + dateOne;
        try {
            Files.createDirectories(Path.of(filePath));
            Files.write(Paths.get(filePath + videoName), file.getBytes());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        List<String> urlList = new ArrayList<>();
        urlList.add(url);
        urlList.add(dateOne + videoName);
        return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_SUCESS, "上传成功", urlList);
    } else {
        return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_FALSE, "该图片格式非法,请上传jpg,png,jpeg图片");
    }
}

public ReturnObject<Object> picDownload(String url, HttpServletResponse response) {
    File f = new File(url);
    if (!f.exists())
        return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_FALSE, "该图片不存在!");
    byte[] bytes = new byte[1024];
    BufferedInputStream bufferedInputStream = null;
    OutputStream outputStream = null;
    FileInputStream fileInputStream = null;
    try {
        fileInputStream = new FileInputStream(f);
        bufferedInputStream = new BufferedInputStream(fileInputStream);

        response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
        response.addHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(f.getName(), "UTF-8"));
        outputStream = response.getOutputStream();
        int length;
        while ((length = bufferedInputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, length);
        }
        outputStream.flush();
    } catch (Exception e) {
        e.getLocalizedMessage();
    } finally {
        try {
            if (bufferedInputStream != null) {
                bufferedInputStream.close();
            }

            if (outputStream != null) {
                outputStream.close();
            }

            if (fileInputStream != null) {
                fileInputStream.close();
            }
        } catch (IOException e) {
            e.getLocalizedMessage();
        }
    }
    return new ReturnObject<>(ConstantOfReturnCode.GLOBAL_RESULT_SUCESS, "下载成功!");
}

public static String getTomcatWabAppsPath() {
    String tomcatRoot = Objects.requireNonNull(FileUploadUtils.class.getClassLoader().getResource("")).getPath();
    String[] foo = tomcatRoot.split("/");
    StringBuilder tomcatWebAppsBuilder = new StringBuilder();
    int i = 0;
    for (String paths : foo) {
        ++i;
        if (i != foo.length) {
            tomcatWebAppsBuilder.append(paths);
            tomcatWebAppsBuilder.append("/");
        }
    }
    return tomcatWebAppsBuilder.toString();
}


/**
 * 多文件上传
 *
 * @param files
 * @param filePath
 * @return
 */
public String uploads(MultipartFile[] files, String filePath) {
    if (files.length == 0) return "files.size=0";
    for (MultipartFile file : files) {
        try {
            byte[] bytes = file.getBytes();
            Path path = Paths.get(filePath + Objects.requireNonNull(file.getOriginalFilename()));
            Files.write(path, bytes);
        } catch (IOException e) {
            log.error(e.getLocalizedMessage(), e);
            return "unsuccessfully";
        }
    }
    return "successfully";
}

public static String getIpAddress() {
    try {
        Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
        InetAddress ip = null;
        while (allNetInterfaces.hasMoreElements()) {
            NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
            if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                continue;
            } else {
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    ip = addresses.nextElement();
                    if (ip != null && ip instanceof Inet4Address) {
                        return ip.getHostAddress();
                    }
                }
            }
        }
    } catch (Exception e) {
        System.err.println("IP地址获取失败" + e.toString());
    }
    return "";
}

}

首先,前端部分可以使用Vue.js框架中的axios库来发送POST请求并上传图片。后端部分可以使用Spring Boot框架中的MultipartFile来处理上传的图片,并使用ResponseEntity返回下载的图片。 以下是一个简单的示例代码: 前端部分: ```javascript <template> <div> <input type="file" ref="fileInput" @change="handleFileUpload"> <button @click="uploadFile">上传</button> <button @click="downloadFile">下载</button> </div> </template> <script> import axios from 'axios' export default { name: 'ImageUpload', data() { return { file: null } }, methods: { handleFileUpload(event) { this.file = event.target.files[0] }, uploadFile() { let formData = new FormData() formData.append('file', this.file) axios.post('/api/upload', formData) .then(response => { console.log(response) }) .catch(error => { console.log(error) }) }, downloadFile() { axios.get('/api/download', { responseType: 'blob' }) .then(response => { const url = window.URL.createObjectURL(new Blob([response.data])) const link = document.createElement('a') link.href = url link.setAttribute('download', 'image.jpg') document.body.appendChild(link) link.click() }) .catch(error => { console.log(error) }) } } } </script> ``` 后端部分: ```java @RestController @RequestMapping("/api") public class ImageController { @PostMapping("/upload") public ResponseEntity<?> uploadImage(@RequestParam("file") MultipartFile file) { // 处理上传的图片 return ResponseEntity.ok().build(); } @GetMapping("/download") public ResponseEntity<byte[]> downloadImage() throws IOException { // 处理下载的图片 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.IMAGE_JPEG); headers.setContentDispositionFormData("attachment", "image.jpg"); byte[] bytes = Files.readAllBytes(Paths.get("path/to/image.jpg")); return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } } ``` 需要注意的是,这只是一个简单的示例代码,实际应用中还需要添加异常处理、文件存储等相关功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值