public String performPost(File file, String url) {
HttpPost httppost = new HttpPost(url);
InputStream content = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("articleattachement[content]", encode(file)));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.d("DEBUG", "UPLOAD: executing request: " + httppost.getRequestLine());
Log.d("DEBUG", "UPLOAD: request: " + httppost.getEntity().getContentType().toString());
content = execute(httppost).getEntity().getContent();
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int len;
while ((len = content.read(buf)) > 0) {
bout.write(buf, 0, len);
}
content.close();
return bout.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String encode(File file) throws IOException {
byte[] data=null;
try {
data = getFileBytes(new FileInputStream(file.getAbsolutePath()));
} catch (Exception e) {
e.printStackTrace();
}
return Base64.encodeToString(data,Base64.URL_SAFE);
}
public byte[] getFileBytes(InputStream ios) throws IOException {
ByteArrayOutputStream ous = null;
//InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
//ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1)
ous.write(buffer, 0, read);
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
// swallow, since not that important
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
// swallow, since not that important
}
}
return ous.toByteArray();
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter