/**
* 上传图片到服务器
* @param webPath 服务器处理地址
* @param uploadFilePath 上传文件地址
* @return
*/
public static String uploadFile(String webPath,String uploadFilePath) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(webPath);
try {
File osFile = new File(uploadFilePath);
if (!osFile.exists()) {
return null;
}
FileBody fileBody = new FileBody(osFile);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
// image 是服务端读取文件的 key
entity.addPart("image", fileBody);
post.setEntity(entity);
HttpResponse response = client.execute(post);
int status = response.getStatusLine().getStatusCode();
if(status == HttpStatus.SC_OK){
//获取服务器返回结果
String result = EntityUtils.toString(response.getEntity(), "utf-8");
Log.e("MyLog", "返回结果:" + result);
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 实现网络访问文件,将获取到的数据保存在指定目录中
* @param url 访问网络的url地址
* @param destFile 保存的文件
* @return
*/
public static boolean loadFileFromURL(String url,File destFile) {
HttpClient httpClient = new DefaultHttpClient();
HttpGet requestGet = new HttpGet(url);
HttpResponse httpResponse = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(destFile));
httpResponse = httpClient.execute(requestGet);
if (httpResponse.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = httpResponse.getEntity();
bis = new BufferedInputStream(entity.getContent());
int len = -1;
byte[] buffer = new byte[8 * 1024];
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
bos.flush();
}
return true;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if(bis != null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return false;
}