Java使用HttpClient上传图片入库和查询数据库获取图片

前言

使用Post请求上传图片到服务端,服务端再插入Oracle
使用Get请求查询数据库图片到服务端,服务端再返回图片

POM文件

<dependencies>
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.12</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.7</version>
    </dependency>
    <dependency>
        <groupId>net.sf.json-lib</groupId>
        <artifactId>json-lib</artifactId>
        <version>2.4</version>
    </dependency>
    <dependency>
        <groupId>top.jfunc.common</groupId>
        <artifactId>converter</artifactId>
        <version>1.8.0</version>
    </dependency>
</dependencies>

一、上传图片

1、代码

客户端

/**
  * @param urlParam 服务端接口地址
  * @param fileUrl  文件地址
  * @return
  * @throws Exception
  */
public static String sendPost(String urlParam, String fileUrl) throws Exception {
    // 创建httpClient实例对象
    CloseableHttpClient httpClient = HttpClients.createDefault();
    // 创建post请求方法实例对象
    HttpPost httpPost = new HttpPost(urlParam);
    File file = new File(fileUrl);
    if(!file.exists()){//判断文件是否存在
        return "文件不存在";
    }
    FileBody bin = new FileBody(file, ContentType.create("image/png", Consts.UTF_8));//创建图片提交主体信息
    HttpEntity entity = MultipartEntityBuilder
            .create()
            .setCharset(Charset.forName("utf-8"))
            .addPart("file",bin)
            .build();
    httpPost.setEntity(entity);
    HttpResponse response = null;   //发送post,并返回一个HttpResponse对象
    try {
        response = httpClient.execute(httpPost);
        if(response.getStatusLine().getStatusCode()==200) {//如果状态码为200,就是正常返回
            String result = EntityUtils.toString(response.getEntity());
            System.out.println(response.getStatusLine().getStatusCode());
            System.out.println(result);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(response.getEntity());
    return "结束";
}

public static void main(String[] args) throws Exception {
    String url1 ="http://localhost:8080/addPic";
    System.out.println(sendPost(url1,"C:\\Users\\37796\\Pictures\\火影\\2.jpg"));
}

服务端

/**
 * @author: Radish
 * @date: 2020-12-14 14:53
 */
@Controller
public class PicController {

    private static final Logger LOGGER = LoggerFactory.getLogger(PicController.class);

    @Autowired
    PicService picService;

    @RequestMapping("/addPic")
    @ResponseBody
    public Object addPic(@RequestParam("file")MultipartFile file, HttpServletRequest request) {
        Map<Object, Object> param = new HashMap<Object, Object>();
        String name = file.getOriginalFilename();
        InputStream stream = null;
        String ioStr = "";
        byte[] in = new byte[0];
        try {
            stream = file.getInputStream();
            //将流转换成String
            in = new byte[stream.available()];
            stream.read(in);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        ImageCenter imageCenter = new ImageCenter();
        imageCenter.setId(1);
        imageCenter.setPictures(in);
        imageCenter.setFilename(UUID.randomUUID().toString()+".jpg");
        picService.addPic(imageCenter);

        return "上传成功!";
    }
}
package com.founder.entity;

/**
 * @author: Radish
 * @date: 2020-12-14 15:29
 */
public class ImageCenter {
    private int id;
    private String filename;
    private byte[] pictures; //用byte[]接收图片数据

    public ImageCenter(){};

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFilename() {
        return filename;
    }

    public void setFilename(String filename) {
        this.filename = filename;
    }

    public byte[] getPictures() {
        return pictures;
    }

    public void setPictures(byte[] pictures) {
        this.pictures = pictures;
    }
}

2、测试

在这里插入图片描述
插入成功!
在这里插入图片描述

二、下载图片

1、代码

客户端

public static List<ImageCenter> sendGet(String urlParam) throws HttpException, IOException {
    // 创建httpClient实例对象
    HttpClient httpClient = new HttpClient();
    // 设置httpClient连接主机服务器超时时间:15000毫秒
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
    // 创建GET请求方法实例对象
    GetMethod getMethod = new GetMethod(urlParam);
    // 设置post请求超时时间
    getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
    getMethod.addRequestHeader("Content-Type", "application/json");

    int i = httpClient.executeMethod(getMethod);
    System.out.println(i);

    List<ImageCenter> picList = null;
    String result = getMethod.getResponseBodyAsString();
    if(result != null && result.length() > 0) {
        picList = JSONArray.parseArray(result, ImageCenter.class);
    }
    return picList;
}

public static void main(String[] args) throws Exception {
    String url2 ="http://localhost:8080/getPic";
    List<ImageCenter> imageCenters = sendGet(url2);
    BufferedOutputStream bos = null;
    FileOutputStream fos = null;
    File file = null;
    byte[] pictures;
    for (ImageCenter imageCenter : imageCenters) {
        System.out.println(imageCenter);
        pictures = imageCenter.getPictures();
        try {
            File dir = new File("C:\\Users\\37796\\Desktop\\pic\\"+imageCenter.getFilename());
            file = new File("C:\\Users\\37796\\Desktop\\pic\\"+imageCenter.getFilename());
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(imageCenter.getPictures());
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
}

服务端

@RequestMapping("/getPic")
@ResponseBody
public List<ImageCenter> getPic() {
    List<ImageCenter> pic = picService.getPic();
    return pic;
}

2、测试

在这里插入图片描述
下载成功!
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值