自己写一个MultipartEntity:
public class MultipartEntity {
private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
.toCharArray();
/**
* 换行符
*/
private final String NEW_LINE_STR = "\r\n";
private final String CONTENT_TYPE = "Content-Type: ";
private final String CONTENT_DISPOSITION = "Content-Disposition: ";
/**
* 文本参数和字符集
*/
private final String TYPE_TEXT_CHARSET = "text/plain; charset=UTF-8";
/**
* GZIP字节流参数
*/
private final String TYPE_GZIP = "application/gzip";
/**
* 字节流参数
*/
private final String TYPE_OCTET_STREAM = "application/octet-stream";
/**
* 二进制参数
*/
private final byte[] BINARY_ENCODING = "Content-Transfer-Encoding: binary\r\n\r\n".getBytes();
/**
* 文本参数
*/
private final byte[] BIT_ENCODING = "Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes();
/**
* 分隔符
*/
private String mBoundary = null;
/**
* 输出流
*/
private ByteArrayOutputStream mOutputStream = new ByteArrayOutputStream();
public MultipartEntity() {
this.mBoundary = generateBoundary();
}
/**
* 生成分隔符
*
* @return
*/
private String generateBoundary() {
final StringBuffer buf = new StringBuffer();
final Random rand = new Random();
for (int i = 0; i < 30; i++) {
buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
}
return buf.toString();
}
/**
* 参数开头的分隔符
*
* @throws IOException
*/
private void writeFirstBoundary() throws IOException {
mOutputStream.write(("--" + mBoundary + "\r\n").getBytes());
}
/**
* 添加文本参数
*
* @param paramName
* @param value
*/
public void addStringPart(final String paramName, final String value) {
writeToOutputStream(paramName, value.getBytes(), TYPE_TEXT_CHARSET, BIT_ENCODING, "");
}
/**
* 将数据写入到输出流中
*
* @param paramName
* @param rawData
* @param type
* @param encodingBytes
* @param fileName
*/
private void writeToOutputStream(String paramName, byte[] rawData, String type,
byte[] encodingBytes,
String fileName) {
try {
writeFirstBoundary();
mOutputStream.write((CONTENT_TYPE + type + NEW_LINE_STR).getBytes());
mOutputStream
.write(getContentDispositionBytes(paramName, fileName));
mOutputStream.write(encodingBytes);
mOutputStream.write(rawData);
mOutputStream.write(NEW_LINE_STR.getBytes());
} catch (final IOException e) {
e.printStackTrace();
}
}
/**
* 添加二进制参数, 例如Bitmap的字节流参数
*
* @param paramName
* @param rawData
*/
public void addBinaryPart(String paramName, final byte[] rawData,String fileName) {
writeToOutputStream(paramName, rawData, TYPE_OCTET_STREAM, BINARY_ENCODING, fileName);
}
/**
* 添加文件参数,可以实现文件上传功能
*
* @param key
* @param file
*/
public void addFilePart(final String key, final File file) {
FileInputStream fin = null;
try {
fin = new FileInputStream(file);
writeFirstBoundary();
final String type;
String fileName = file.getName();
boolean isGzip=fileName.endsWith(".gz");
if (isGzip) {
type = CONTENT_TYPE + TYPE_GZIP + NEW_LINE_STR;
}else{
type = CONTENT_TYPE + TYPE_OCTET_STREAM + NEW_LINE_STR;
}
mOutputStream.write(getContentDispositionBytes(key, file.getName()));
mOutputStream.write(type.getBytes());
mOutputStream.write(BINARY_ENCODING);
final byte[] tmp = new byte[4096];
int len = 0;
while ((len = fin.read(tmp)) != -1) {
mOutputStream.write(tmp, 0, len);
}
if(isGzip){
mOutputStream.write(NEW_LINE_STR.getBytes());
}
mOutputStream.flush();
} catch (final IOException e) {
e.printStackTrace();
} finally {
closeSilently(fin);
}
}
private void closeSilently(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
} catch (final IOException e) {
e.printStackTrace();
}
}
private byte[] getContentDispositionBytes(String paramName, String fileName) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(CONTENT_DISPOSITION + "form-data; name=\"" + paramName + "\"");
// 文本参数没有filename参数,设置为空即可
if (!TextUtils.isEmpty(fileName)) {
stringBuilder.append("; filename=\""
+ fileName + "\"");
}
return stringBuilder.append(NEW_LINE_STR).toString().getBytes();
}
public String getContentType() {
return "multipart/form-data; boundary=" + mBoundary;
// return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + mBoundary);
}
public void writeTo(final OutputStream outstream) throws IOException {
// 参数最末尾的结束符
final String endString = "--" + mBoundary + "--\r\n";
// 写入结束符
mOutputStream.write(endString.getBytes());
//
outstream.write(getOutputBytes());
}
public InputStream getContent() {
return new ByteArrayInputStream(getOutputBytes());
}
private byte[] getOutputBytes() {
return mOutputStream.toByteArray();
}
}
上传图片工具类:
public class FileImageUpload {
private static final String TAG = FileImageUpload.class.getSimpleName();
public static String uploadFile(File file, String requestURL, String cookie) {
LogUtils.d(TAG, "updateAvatar requestURL = " + requestURL + "; \n cookie = " + cookie);
String result = "";
MultipartEntity multiPart = new MultipartEntity();
HttpURLConnection conn = null;
OutputStream output;
try {
URL url = new URL(requestURL);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(30 * 1000);
conn.setDoInput(true);// 允许输入
conn.setDoOutput(true);// 允许输出
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST");
conn.addRequestProperty("Cookie", cookie);
conn.addRequestProperty("Content-Type", multiPart.getContentType());
conn.connect();
output = conn.getOutputStream();
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bao);
multiPart.addBinaryPart("file", bao.toByteArray(), "abc.jpg");
multiPart.addStringPart("appid", "100106");
// 写入multipart
multiPart.writeTo(output);
output.flush();
int res = conn.getResponseCode();
if (res == 200) {
InputStream in = conn.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
buffer.append(line);
}
result = buffer.toString();
in.close();
}
output.close();
} catch (Exception e) {
LogUtils.d(TAG, "uploadAvatar ClientProtocolException = " + e.toString());
result = e.getMessage();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return result;
}
}
Relate:
android upload image using MultipartEntity
Android使用post方式上传图片到服务器的方法