设为首页 加入收藏

TOP

从相册获取图片及调用相机拍照获取图片,最后上传图片到服务器(二)
2017-10-13 10:47:30 】 浏览:8567
Tags:相册 获取 图片 调用 相机 拍照 最后 上传 服务器
;>();
params.put("mid", mSzId);// 上传参数
Map<String, File> files = new HashMap<>();
files.put("myUpload", new File(mImgUrlPath));// 上传文件路径
try {
String json = NetUtil.uploadFile(Constants.URL_EDIT_IMG, params, files);
//json为服务器返回的数据,可自己解析(如json解析)取得想要的数据
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
};
 
保存图片和上传图片的工具类NetUtil :
public class NetUtil {
// 上传图片到服务器
public static String uploadFile(String url, Map<String, String> params, Map<String, File> files)
throws IOException {
String tempStr = null;
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--", LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
HttpURLConnection conn = null;
try {
URL uri = new URL(url);
conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(10 * 1000); // 缓存的最长时间
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
// 首先组拼文本类型的参数
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET + LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
LogUtil.e("NetUtil", "uploadFile sb:" + sb.toString());
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
// 发送文件数据
if (files != null)
for (Map.Entry<String, File> file : files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name="+file.getKey() +"; filename=\""
+ file.getValue() + "\"" + LINEND);
sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND);
sb1.append(LINEND);
LogUtil.e("NetUtil", "uploadFile sb1:" + sb1.toString());
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
// 请求结束标志
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
outStream.close();
StringBuilder sb2 = new StringBuild
首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇Android高效计算——RenderScript.. 下一篇Android---闪频页和倒计时

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目