public static Map<String,Object> UpIOFile(byte[] bbyte,String type){
String uploadUrl = "上传到的地址";
String end = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------823928434";
try {
URL url = new URL(uploadUrl);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());
dos.writeBytes(twoHyphens + boundary + end);
dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\"test."+type+"\"" + end);
dos.writeBytes(end);
dos.write(bbyte);
dos.writeBytes(end);
dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
dos.flush();
// 读取服务器返回结果
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is, "utf-8");
BufferedReader br = new BufferedReader(isr);
String result = br.readLine();
is.close();
Map<String,Object> resultMap = JSON.parseObject(result,Map.class);
return resultMap;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//图片转为file格式
File file = FileUtil.file(spreadPicPath);
FileInputStream fileInputStream = new FileInputStream(file);
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fileInputStream.read(buffer)) != -1) {
//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度
outStream.write(buffer, 0, len);
}
Map<String, Object> map = MutiPartFileUtil.UpIOFile(outStream.toByteArray(), "jpg");
map.put("url",map.get("url"));