SpringBoot realiza o upload de fotos

Recentemente, há uma demanda: upload de fotos. Aqui está uma breve introdução ao código principal.

//上传图片
public BaseResponse uploadPicture(MultipartFile file, HttpServletRequest request, 									   HttpServletResponse response) {
    
    

        File targetFile = null;
        String url = "";//存储路径
        String fileName = file.getOriginalFilename();//获取文件名加后缀
        if (fileName != null && fileName != "") {
    
    
            String path = "/root/container/nginx/data/dist_20201217/";
            //String path = "D:/data/file/";
            String fileF = fileName.substring(fileName.lastIndexOf("."), fileName.length());//文件后缀
            if (!(fileF.equals(".jpg") || fileF.equals(".jpeg") || fileF.equals(".png") || fileF.equals(".image"))) {
    
    
                return new BaseResponse(StatusCode.Fail, "只能上传jpg,jpeg,png,image格式");
            }
            //新的文件名
            fileName = new Date().getTime() + "_" + new Random().nextInt(1000) + fileF;
            //获取文件夹路径
            File file1 = new File(path);
            //如果文件夹不存在则创建
            if (!file1.exists() && !file1.isDirectory()) {
    
    
                file1.mkdirs();
            }
            //将图片存入文件夹
            targetFile = new File(file1, fileName);
            try {
    
    
                //将上传的文件写到服务器上指定的文件。
                file.transferTo(targetFile);
                //赋予权限
                String command = "chmod 775 -R " + targetFile;
                Runtime runtime = Runtime.getRuntime();
                Process proc = runtime.exec(command);
                //生成文件地址
                //url = "http://xxxxxx" + path + "/" + fileName;
                
                //这里的xxxxxxxxx是服务器的ip
                //我这里使用的服务器中,在nginx中配置了存放图片的路径,通过80端口qr_code映射服务				//器上的路径
                url = "http://xxxxxxxxx/qr_code"  + "/" + fileName;
                return new BaseResponse(StatusCode.Success, url);
            } catch (Exception e) {
    
    
                e.printStackTrace();
                return new BaseResponse(StatusCode.Fail, "系统异常,图片上传失败");
            }
        }
        return null;
    }

Este é o arquivo de configuração do nginx no servidor: nginx.conf

[Falha na transferência da imagem do link externo. O site de origem pode ter um mecanismo anti-hotlink. Recomenda-se salvar a imagem e carregá-la diretamente (img-u3YnAthv-1615950622397) (C: \ Usuários \ 程 梦 月 \ AppData \ Roaming \ Typora \ typora-user-images \ image-20210317110408561.png)]
Use / qr_code para mapear o caminho no servidor / root / container / nginx / data / dist_20201217 /

Se você não entende isso, pode verificar o nginx.

Após a aprovação do teste de interface, o endereço de url será retornado e podemos visitar diretamente o url retornado para ver a imagem.

Aqui, vamos testar para salvar a imagem em um caminho local.

1. Altere o caminho para seu próprio diretório local.

           	 	String path = "D:/data/file/";

2. Comente as três linhas de permissão a seguir

      			//赋予权限
				//String command = "chmod 775 -R " + targetFile;
				//Runtime runtime = Runtime.getRuntime();
				//Process proc = runtime.exec(command);
                //生成文件地址
                url = path + "/" + fileName;

Teste a interface para ver se há imagens em seu caminho local.

Insira a descrição da imagem aqui

Acho que você gosta

Origin blog.csdn.net/hello_cmy/article/details/114920418
Recomendado
Clasificación