文件以2进制上服务器,图片转二进制流并通过HTTP上传到静态文件服务器

1 图片转化成base64字符串

//图片转化成base64字符串

public static String getImageBinary(String imgFile){

BASE64Encoder encoder = new sun.misc.BASE64Encoder();

File f = new File(imgFile);

BufferedImage bi;

try {

bi = ImageIO.read(f);

ByteArrayOutputStream baos = new ByteArrayOutputStream();

ImageIO.write(bi, "jpg", baos);

byte[] bytes = baos.toByteArray();

return encoder.encodeBuffer(bytes).trim();

} catch (IOException e) {

e.printStackTrace();

}

return "";

}

注意:在图片转成base64String中可能会包含\r\n,要将其去掉

String imageBinary = base64String.replaceAll("\r\n", "").replaceAll("\r", "").replaceAll("\n", "");

2 base64字符串转化成图片

//base64字符串转化成图片

public static boolean GenerateImage(String imgStr, String imgFilePath, String imgFileName) {

//对字节数组字符串进行Base64解码并生成图片

//图像数据为空

if (imgStr == null) {

return false;

}

if(imgFilePath == null || imgFileName == null) { // 存储路径为空

return false;

}

File filePath = new File(imgFilePath);

if(!filePath.exists()) {

filePath.mkdirs();

}

imgFilePath = imgFilePath + imgFileName;

BASE64Decoder decoder = new BASE64Decoder();

try {

//Base64解码

byte[] b = decoder.decodeBuffer(imgStr);

for(int i=0;i

if(b[i]<0) {//调整异常数据

b[i]+=256;

}

}

//生成jpeg图片

//String imgFilePath = "d://222.jpg";//新生成的图片

OutputStream out = new FileOutputStream(imgFilePath);

out.write(b);

out.flush();

out.close();

return true;

} catch (Exception e) {

return false;

}

}

imgFileName后面记得加.jpg

3 post方法采用的okhttp3

/**

* POST TO A SERVER

* @param url

* @param data

* @return

* @throws IOException

*/

public static String postRequest(String url,String data,MediaType type)throws IOException {

OkHttpClient client = new OkHttpClient();

RequestBody body = RequestBody.create(type, data);

Request request = new Request.Builder()

.url(url)

.post(body)

.build();

Response response = client.newCall(request).execute();

if(response.isSuccessful()){

ResponseBody responseBody = response.body();

if (responseBody != null) {

// 返回的是string 类型

String str = responseBody.string();

logger.debug("getPostRequest response =>" + str);

return str;

}

}

return null;

}

type设置为MediaType.parse("application/json; charset=utf-8")

data是我封装的json字符串,把base64String键值进去。接口端直接解析data就行。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值