图片上传及访问

通过spring-boot实现文件上传到服务器上,并将链接保存在数据库中

新手操作请先看这篇: sprint-boot实现第一个api

application.properties 部分配置

ip=***.**.***.***
#图片存储的位置
image-save-path=/data/images/

ImageController

package com.example.demo.controller;

import com.example.demo.model.Image;
import com.example.demo.result.Result;
import com.example.demo.result.ResultGenerator;
import com.example.demo.server.ImageServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@RestController
public class ImageController {

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 图片保存路径
     */
    @Value("${image-save-path}")
    private String imageSavePath;

    @Value("${ip}")
    private String ip;

    @Value("${server.port}")
    private String port;

    @Autowired
    private ImageServer imageServer;

    @RequestMapping(value = "upload/image", method = RequestMethod.POST)
    public Result uploadImage(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return ResultGenerator.getFailResult("图片为空");
        }

        //1. 后半段目录
        String directory = simpleDateFormat.format(new Date());

        //2.文件保存目录
        File dir = new File(imageSavePath + directory);
        if (!dir.exists()) {
            dir.mkdir();
        }

        //3.给文件重新设置一个名字
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString().replace("-", "") + suffix;

        //4.创建这个新文件
        File newFile = new File(imageSavePath + directory + "/" + newFileName);

        //5.复制操作
        try {
            file.transferTo(newFile);
            String url = "http://" + ip + ":" + port + "/images/" + directory + "/" + newFileName;
            Image image = new Image();
            image.setUrl(url);
            imageServer.saveUrl(image);
            return ResultGenerator.getSuccessResult(url);
        } catch (IOException e) {
            return ResultGenerator.getFailResult(newFile.exists() + " " + e.getMessage());
        }
    }
}

资源文件映射

为什么需要这个?

可以看到图片上传存储的实际位置是 /data/images/yyyy-MM-dd/xxx.jpg

我们无法直接通过 url 来访问

@Configuration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 图片保存路径
     */
    @Value("${image-save-path}")
    private String imageSavePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/images/**")
                .addResourceLocations("file://" + imageSavePath);
    }
}

资源文件配置失效解决思路

本地 java 上传文件

private static void postImage() {
    HttpClient httpClient = HttpClientBuilder.create().build();
    HttpPost httpPost = new HttpPost(url+"/upload/image");
    MultipartEntityBuilder meb = MultipartEntityBuilder.create();
    meb.addBinaryBody("file",new File("C:\\Users\\花染梦\\Desktop\\0.png"));
    HttpEntity httpEntity = meb.build();
    System.out.println(httpEntity);
    httpPost.setEntity(httpEntity);
    try{
        StringBuilder sb = new StringBuilder();
        String line;
        HttpResponse httpResponse = httpClient.execute(httpPost);
        InputStream is = httpResponse.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        while((line=br.readLine())!=null){
            sb.append(line);
        }
        String msg = URLDecoder.decode(sb.toString(),"UTF-8");
        System.out.println(msg);
    }catch (IOException e){
        e.printStackTrace();
    }
}

返回的 url : http://*****/images/2021-02-10/0692064e49d14dbaaf14c2e41d99639d.png

请特别注意:这里返回的是http,而不是 https,原因在于网站没有签发信任SSL证书的情况下,不能通过 https 访问图片

posted @ 2021-02-10 22:59  花染梦  阅读(331)  评论(0编辑  收藏  举报