最近在做一个Android项目,用到一个文件上传的功能,开始用的方法是用HttpURLConnection实现的,但是因为项目的原因,需要上传一些大文件,于是便遇到了OOM问题。
为了解决这个问题,自己网上查找了一些资料,有一种方法是对大文件进行分割,但是要做的改动比较大,因为牵扯到服务端的功能。
参考链接1
为了解决这个问题,自己网上查找了一些资料,有一种方法是对大文件进行分割,但是要做的改动比较大,因为牵扯到服务端的功能。
而另一种方法就是使用Apache HttpComponents的组件HttpClient来进行文件上传处理。首先要下载一个官方jar包,导入工程中。
/***
* 上传大文件方法
* @param params 上传文件附带的一些参数
* @param files 文件名和文件
* @return
*/
private String uploadfile(Map<String, String> params, Map<String, File> files){
//初始化参数
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--";
String LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
String data = null;//定义返回值
HttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
client.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "utf-8");
try {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE,BOUNDARY, Charset.defaultCharset());
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
for(Map.Entry<String, String> tmp : params.entrySet()){
//添加与文件有关的参数
entity.addPart(tmp.getKey(), new StringBody(tmp.getValue(), Charset.forName("UTF-8")));
}
for(Map.Entry<String, File> tmp : files.entrySet()){
//添加要上传的文件
entity.addPart(tmp.getKey(), new FileBody(tmp.getValue()));
}
httpPost.setEntity(entity);
HttpResponse response = client.execute(httpPost);
if (response.getStatusLine().getStatusCode() == 200) { // 成功
InputStream in = response.getEntity().getContent();
InputStreamReader isReader = new InputStreamReader(in);
BufferedReader bufReader = new BufferedReader(isReader);
String line = null;
while ((line = bufReader.readLine()) != null)
{
//获取服务器的返回值
data = line;
}
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
参考链接1