【Java】Fazer upload e download de imagens ou arquivos


Prefácio

Durante o processo de desenvolvimento, muitas vezes é necessário retornar arquivos ou imagens diretamente chamando o endereço da interface de back-end.Este artigo é usado como exemplo de referência do código que usei durante o processo de desenvolvimento;


1. Carregamento de imagem

Nem preciso dizer mais nada, basta acessar o código:

    /**
     * 图片上传
     *
     * @param file 图片
     * @return JSON
     */
    (value = "/uplloadSystemPictures")
    public JSONObject uplloadSystemPictures((value = "file", required = false) MultipartFile file) {
    
    
        File targetFile;
        Object url = null;//返回存储路径
        String fileName = file.getOriginalFilename();//获取文件名加后缀
        if (fileName != null && !"".equals(fileName)) {
    
    
            //获取文件存储路径,这里也可以写死,我是存在配置中的;
            String path = wccs.findValueByName(PropertiesReader.getString("ICON_IMAGE_URL")); //文件存储位置
            log.info("文件存储位置 == {}", path);
            String fileF = fileName.substring(fileName.lastIndexOf("."));//文件后缀
            fileName = UUID.randomUUID().toString() + fileF;//新的文件名
            log.info("文件名称 == {}", fileName);
            //获取文件夹路径
            File file1 = new File(path);
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            //将上传的文件写到服务器上指定的文件。
            try {
    
    
                file.transferTo(targetFile);
            } catch (IOException e) {
    
    
                log.error("文件上传至服务器异常 == {}", e.getMessage());
                e.printStackTrace();
            }
            //我这里是获取系统配置的域名+下方的读取的接口名称,然后再加上文件名称;上传成功后,就返回这个地址给前端,前端就能调用了;
            url = wccs.findValueByName(PropertiesReader.getString("ICON_READ_IMAGE_URL")) + fileName;
        }
        return ResJsonUtil.toJsonSuccess(url);
    }

2. Leitura e download de imagens

código mostrado abaixo:

    /**
     * 读取图片
     * 请求地址中的fileName也就是文件名称以及文件格式了,例如:http://localhost:5780/getImage/355548sd.png 这种格式调用接口;根据传入的文件名称,去获取对应的文件;名称是通过上传的接口获取的哈,请看上一步
     * @param fileName 图片名称
     * @param response response
     */
    (value = "/getImage/{fileName:.+}")
    (value = "*", allowCredentials = "true")
    public void getImage( String fileName, HttpServletResponse response) {
    
    
        FileInputStream fis = null;
        try {
    
    
            OutputStream out = response.getOutputStream();
            //获取配置中的图片地址
            String addRess = wccs.findValueByName(PropertiesReader.getString("ICON_IMAGE_URL")) + "\\" + fileName;
            log.info("获取到的文件名称 == {}", fileName);
            File file = new File(addRess);
            fis = new FileInputStream(file);
            byte[] b = new byte[fis.available()];
            fis.read(b);
            out.write(b);
            out.flush();
        } catch (Exception e) {
    
    
            log.error("读取图片失败异常 == {}", e.getMessage());
        } finally {
    
    
            if (fis != null) {
    
    
                try {
    
    
                    fis.close();
                } catch (IOException io) {
    
    
                    log.error("返回图片关闭流异常 == {}", io.getMessage());
                }
            }
        }
    }

Resumir

A função é muito simples, apenas este pedaço de código; se você mesmo escrever, poderá otimizar o código. Para meu projeto antigo, não importa o que escrevi antes; é apenas para conveniência de exibição;

Supongo que te gusta

Origin blog.csdn.net/qq_42666609/article/details/132079115
Recomendado
Clasificación