`
zhouxingfu520
  • 浏览: 418489 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

http 使用BASE64发送图片

    博客分类:
  • java
阅读更多

服务器端 方法内代码

String fileName = request.getParameter("fileName");
String str = request.getParameter("file");
log.info(fileName+"------------");
log.info(str+"-==================");             
BASE64Decoder decoder = new BASE64Decoder();
	        try {
	            // Base64解码
	            byte[] bytes = decoder.decodeBuffer(str);
	            for (int i = 0; i < bytes.length; ++i) {
	                if (bytes[i] < 0) {// 调整异常数据
	                    bytes[i] += 256;
	                }
	            }
	            // 生成图片
	            OutputStream outs = new FileOutputStream(filepath+fileName);
	            outs.write(bytes);
	            outs.flush();
	            outs.close();
    		    return null;
	        } catch (Exception e) {
                     logger.error("", e);
	        }

 

客户调用端

public static String getPicBASE64() {
		String picPath = "/var/xxxx.png";
		String content = "";
		try {
			FileInputStream fileForInput = new FileInputStream(picPath);
			byte[] bytes = new byte[fileForInput.available()];
			if(bytes.length<102400){
				System.out.print(bytes.length);
			}
			fileForInput.read(bytes);
		content = new sun.misc.BASE64Encoder().encode(bytes); // 具体的编码方法
			fileForInput.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}

	public static void main(String[] args) throws Exception {


		URL url = new URL("http://**********:80/newdemo/app/imageUpload.do");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setDoOutput(true);
		connection.setDoInput(true);
		// Post 请求不能使用缓存
		connection.setUseCaches(false);
// URLConnection.setFollowRedirects是static函数,作用于所有的URLConnection对象。
		// connection.setFollowRedirects(true);
		// URLConnection.setInstanceFollowRedirects是成员函数,仅作用于当前函数
		connection.setInstanceFollowRedirects(false);
		// 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的
// 正文是urlencoded编码过的form参数,下面我们可以看到我们对正文内容使用URLEncoder.encode
		// 进行编码
		connection.setRequestProperty("Content-Type",
				"application/x-www-form-urlencoded");
		// 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成,
		// 要注意的是connection.getOutputStream会隐含的进行connect。
		connection.connect();
		Long sendTime = System.currentTimeMillis();
		DataOutputStream out = new DataOutputStream(
				connection.getOutputStream());
		// 要传的参数
		String content ="fileName=ssh2.jpg";
		// 得到图片的base64编码
		content = content + "&" + URLEncoder.encode("file", "UTF-8") + "="+ URLEncoder.encode(getPicBASE64(), "UTF-8");
		out.writeBytes(content);
		out.flush();
		out.close(); 
			}

		
	}

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics