我有个图片上传服务器的demo 但用的是HttpConnection来做的
解决方案 »
- android菜鸟遇到个关于内部类的问题
- 一个安卓效果
- SKIA源代码发现的两处内存泄露及解决方法!
- android模拟器程序运行时出现The application has stopped unexpectedly,please try again
- android通过post传参保存参数值到.net后台数据库怎么实现?
- 能改android系统图标吗?还有删除或修改任务栏图片 比如修改电池的图片
- 写Hello World 程序遇到如下问题,求解
- Android 遍历多叉树 打印根节点到子节点
- 蘑菇街开源的 IM 项目 TeamTalk,包括 Android、iOS、Win、Mac 客户端以及 Server端、管理后台、环境自动部署,大赞!
- android EditView游标位置
- android静默卸载怎么实现?
- sqlite 查询 遍历 datetime
* 上传文件到服务器
* @param file
* @return
* @throws Exception
*/
public Json uploadLocal(File file) throws Exception {
fileSize = (int) file.length();
if (null != progress) {progress.setMax(fileSize);}
String url = "http://192.168.1.58:8088/test/other/httpTakeFile.htm";
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
conn.setDoOutput(true);conn.setDoInput(true);
conn.setChunkedStreamingMode(1024 * 1024);
conn.setRequestMethod(Domain.REQUEST_POST);
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charsert", HTTP.UTF_8);
conn.setRequestProperty("Content-Type", "multipart/form-data;file=" + file.getName());
conn.setRequestProperty("ext", file.getName().substring(file.getName().lastIndexOf(".")));
OutputStream output = conn.getOutputStream();InputStream input = new FileInputStream(file);
int i = 0, total = 0;
byte[] buffer = new byte[1024];
while ((i = input.read(buffer)) != -1) {
output.write(buffer, 0, i);
total += i;
if (null != progress) {progress.setProgress(total);}
}
String response = readFile(conn.getInputStream(), HTTP.UTF_8, 1, false);
input.close();output.flush();output.close();conn.disconnect();
JSONObject object = new JSONObject(response);
Json vo = new Json(object.getBoolean("success"), object.getString("message"));
JSONObject data = null;try {data = (JSONObject) object.get("data");} catch (Exception e) {}
if (null != data) {
Iterator iterator = data.keys();
while (iterator.hasNext()) {
String key = (String) iterator.next();vo.getData().put(key, data.get(key));
}
}
return vo;
}服务器端代码:
/**
* http上传文件
* @return
*/
public Json httpTakeFile() {
try {
CommUtil.checkRequestMethod(Constant.REQUEST_POST);
String folder = FileUtil.UPLOAD_TEMP_PATH + "10/";
return new Json(true, Json.OPERATE_RIGHT_MESSAGE).
addData("fileUrl", FileUtil.readRootUrl() + folder + FileUtil.httpTakeFile(FileUtil.getBasePath() + folder));
} catch (Exception e) {
log.error("http上传文件", e);
return new Json(false, e.getMessage());
}
}