开发记录 === python脚本图片上传到Java后端在MongoDB存储

当前需求:python爬取图片后到后端进行存储到MongoDB
第一次做全栈图片存储的项目,记录一下

@Data
@Document
@Accessors(chain = true)
public class PicUpload implements Serializable {
    @Id
    private String id;
    private Binary content;
    private String contentType;
}


这个是MongoDB存储的对象格式
response = requests.get("https://img2.baidu.com/it/u=1685092271,2574681286&fm=253&fmt=auto&app=120&f=JPEG?w=1200&h=797").content
requests.post(url="http://localhost:8080/test",data=response)


python的脚本只做个示例,第一行是获取图片的二进制数据,第二行是把二进制数据发到后端接口去,具体处理方法看后端
private final MongoTemplate mongoTemplate;

    /**
     * 图片上传
     */
    @PostMapping("/uploadFolder")
    public String uploadImage(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = request.getInputStream();
        Binary binary = new Binary(toByteArray(inputStream));
        PicUpload picUpload = new PicUpload()
                .setContent(binary)
                .setContentType("image/jpeg");
        PicUpload savedFile = mongoTemplate.save(picUpload);
        return savedFile.getId();
    }

    /**
     * 获取图片
     */
    @GetMapping(value = "/image/{id}", produces = {MediaType.IMAGE_JPEG_VALUE, MediaType.IMAGE_PNG_VALUE})
    public byte[] image(@PathVariable("id") String id) {
        byte[] data = null;
        PicUpload file = mongoTemplate.findById(id, PicUpload.class);
        if (file != null) {
            data = file.getContent().getData();
        }
        return data;
    }

    public static byte[] toByteArray(InputStream input) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024*4];
        int n = 0;
        while (-1 != (n = input.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }



第一个方法:获取python传来的二进制数据并通过第三个方法转为byte数据再封装成Binary进行存储即可
第二个方法:看图片的,浏览器直接访问就可以看到了
第三个方法:把inputStream转为byte

并没有什么难点,主要是第一次,记录一下

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值