两种android客户端传图片的方法
2016-09-17 13:14
375 查看
版权声明:本文为博主原创文章,未经博主允许不得转载。
///////////2016/03/14///////////
/////////by xbw/////////////////
/////////环境 eclipse php//
第一种,‘
一个类FileUtil
[java]
view plain
copy
print?
package com.example.image_head;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
public class FileUtil {
public static String saveFile(Context c, String fileName, Bitmap bitmap) {
return saveFile(c, "", fileName, bitmap);
}
public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {
byte[] bytes = bitmapToBytes(bitmap);
return saveFile(c, filePath, fileName, bytes);
}
public static byte[] bitmapToBytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, baos);
return baos.toByteArray();
}
public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
String fileFullName = "";
FileOutputStream fos = null;
String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)
.format(new Date());
try {
String suffix = "";
if (filePath == null || filePath.trim().length() == 0) {
filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/";
}
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
File fullFile = new File(filePath, fileName + suffix);
fileFullName = fullFile.getPath();
fos = new FileOutputStream(new File(filePath, fileName + suffix));
fos.write(bytes);
} catch (Exception e) {
fileFullName = "";
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
fileFullName = "";
}
}
}
return fileFullName;
}
}
第二个类 NetUtil
[java]
view plain
copy
print?
package com.example.image_head;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class NetUtil {
// 一般来说用一个生成一个UUID的话,会可靠很多,这里就不考虑这个了
// 而且一般来说上传文件最好用BASE64进行编码,你只要用BASE64不用的符号就可以保证不冲突了。
// 尤其是上传二进制文件时,其中很可能有\r、\n之类的控制字符,有时还可能出现最高位被错误处理的问题,所以必须进行编码。
public static final String BOUNDARY = "--my_boundary--";
/**
* 普通字符串数据
* @param textParams
* @param ds
* @throws Exception
*/
public static void writeStringParams(Map<String, String> textParams,
DataOutputStream ds) throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + BOUNDARY + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
ds.writeBytes("\r\n");
value = value + "\r\n";
ds.write(value.getBytes());
}
}
/**
* 文件数据
* @param fileparams
* @param ds
* @throws Exception
*/
public static void writeFileParams(Map<String, File> fileparams,
DataOutputStream ds) throws Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
File value = fileparams.get(name);
ds.writeBytes("--" + BOUNDARY + "\r\n");
//uploadedfile与服务器端内容匹配
ds.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
+ URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n");
ds.writeBytes("Content-Type:application/octet-stream \r\n");
ds.writeBytes("\r\n");
ds.write(getBytes(value));
ds.writeBytes("\r\n");
}
}
// 把文件转换成字节数组
private static byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
/**
* 添加结尾数据
* @param ds
* @throws Exception
*/
public static void paramsEnd(DataOutputStream ds) throws Exception {
ds.writeBytes("--" + BOUNDARY + "--" + "\r\n");
ds.writeBytes("\r\n");
}
public static String readString(InputStream is) {
return new String(readBytes(is));
}
public static byte[] readBytes(InputStream is) {
try {
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
方法,在button的点击事件中添加线程
[java]
view plain
copy
print?
new Thread(uploadImageRunnable).start();
[java]
view plain
copy
print?
Runnable uploadImageRunnable = new Runnable() {
@Override
public void run() {
if(TextUtils.isEmpty(imgUrl)){//php服务器端url
Toast.makeText(getActivity(), "还没有设置上传服务器的路径!", Toast.LENGTH_SHORT).show();
return;
}
Map<String, String> textParams = new HashMap<String, String>();
Map<String, File> fileparams = new HashMap<String, File>();
try {
// 创建一个URL对象
URL url = new URL(imgUrl);
textParams = new HashMap<String, String>();
fileparams = new HashMap<String, File>();
// 要上传的图片文件
File file = new File(urlpath);//本地图片路径
fileparams.put("image", file);
// 利用HttpURLConnection对象从网络中获取网页数据
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置连接超时(记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作)
conn.setConnectTimeout(5000);
// 设置允许输出(发送POST请求必须设置允许输出)
conn.setDoOutput(true);
// 设置使用POST的方式发送
conn.setRequestMethod("POST");
// 设置不使用缓存(容易出现问题)
conn.setUseCaches(false);
conn.setRequestProperty("Charset", "UTF-8");//设置编码
// 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头
conn.setRequestProperty("ser-Agent", "Fiddler");
// 设置contentType
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);
OutputStream os = conn.getOutputStream();
DataOutputStream ds = new DataOutputStream(os);
NetUtil.writeStringParams(textParams, ds);
NetUtil.writeFileParams(fileparams, ds);
NetUtil.paramsEnd(ds);
// 对文件流操作完,要记得及时关闭
os.close();
// 服务器返回的响应吗
int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来
// 对响应码进行判断
if (code == 200) {// 返回的响应码200,是成功
// 得到网络返回的输入流
InputStream is = conn.getInputStream();
resultStr = NetUtil.readString(is);
} else {
Toast.makeText(getActivity(), "请求URL失败!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
};
[java]
view plain
copy
print?
这样就好了
第二种。
在button监听事件中添加
[java]
view plain
copy
print?
new Task().execute();
[java]
view plain
copy
print?
class Task extends AsyncTask<String, Integer, Integer> {
@Override
protected Integer doInBackground(String... strings) {
Integer result = -1;
try {
result = UpFile.post(config_a.uploadUrl,
new File("/storage/extSdCard/b.png"));//本地图片路径
}
catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(Integer result) {
Toast.makeText(getActivity(), "" + result, Toast.LENGTH_LONG).show();
}
}
Upload_image.java类
[java]
view plain
copy
print?
package com.example.image_head;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
import com.example.configs.config_a;
import android.widget.Toast;
public class Upload_image {
public static class UpFile {
public static int post(String actionUrl, File file) throws IOException {
//产生随机分隔内容
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX = "--";
String LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL url = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时时间单位是毫秒
conn.setReadTimeout(5 * 1000);
//设置允许输入
conn.setDoInput(true);
//设置允许输出
conn.setDoOutput(true);
//不允许使用缓存
conn.setUseCaches(false);
//设置请求的方法为Post
conn.setRequestMethod("POST");
//设置维持长连接
conn.setRequestProperty("Connection", "keep-alive");
//设置字符集为UTF-8
conn.setRequestProperty("Charset", CHARSET);
//设置文件的类型
conn.setRequestProperty("Content-type", MULTIPART_FROM_DATA + "; boundary=" + BOUNDARY);
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
//发送文件数据
if (file != null) {
StringBuilder sb = new StringBuilder();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
//uploadedfile与服务器端内容匹配
sb.append("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + file.getName() + "\"" + LINEND);
//
sb.append("Content-Type: image/png" + LINEND);
sb.append(LINEND);
//写入输出流中
outStream.write(sb.toString().getBytes());
//将文件读入输入流中
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
//写入输出流中
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
//添加换行标识
outStream.write(LINEND.getBytes());
}
byte[] endData = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(endData);
//发送数据
outStream.flush();
//获取响应码 上传成功返回的是200
int res = conn.getResponseCode();
return res;
}
}
}
这样也能成功,
///////////2016/03/14///////////
/////////by xbw/////////////////
/////////环境 eclipse php//
第一种,‘
一个类FileUtil
[java]
view plain
copy
print?
package com.example.image_head;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.os.Environment;
public class FileUtil {
public static String saveFile(Context c, String fileName, Bitmap bitmap) {
return saveFile(c, "", fileName, bitmap);
}
public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) {
byte[] bytes = bitmapToBytes(bitmap);
return saveFile(c, filePath, fileName, bytes);
}
public static byte[] bitmapToBytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 100, baos);
return baos.toByteArray();
}
public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) {
String fileFullName = "";
FileOutputStream fos = null;
String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA)
.format(new Date());
try {
String suffix = "";
if (filePath == null || filePath.trim().length() == 0) {
filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/";
}
File file = new File(filePath);
if (!file.exists()) {
file.mkdirs();
}
File fullFile = new File(filePath, fileName + suffix);
fileFullName = fullFile.getPath();
fos = new FileOutputStream(new File(filePath, fileName + suffix));
fos.write(bytes);
} catch (Exception e) {
fileFullName = "";
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
fileFullName = "";
}
}
}
return fileFullName;
}
}
package com.example.image_head; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.os.Environment; public class FileUtil { public static String saveFile(Context c, String fileName, Bitmap bitmap) { return saveFile(c, "", fileName, bitmap); } public static String saveFile(Context c, String filePath, String fileName, Bitmap bitmap) { byte[] bytes = bitmapToBytes(bitmap); return saveFile(c, filePath, fileName, bytes); } public static byte[] bitmapToBytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(CompressFormat.JPEG, 100, baos); return baos.toByteArray(); } public static String saveFile(Context c, String filePath, String fileName, byte[] bytes) { String fileFullName = ""; FileOutputStream fos = null; String dateFolder = new SimpleDateFormat("yyyyMMdd", Locale.CHINA) .format(new Date()); try { String suffix = ""; if (filePath == null || filePath.trim().length() == 0) { filePath = Environment.getExternalStorageDirectory() + "/JiaXT/" + dateFolder + "/"; } File file = new File(filePath); if (!file.exists()) { file.mkdirs(); } File fullFile = new File(filePath, fileName + suffix); fileFullName = fullFile.getPath(); fos = new FileOutputStream(new File(filePath, fileName + suffix)); fos.write(bytes); } catch (Exception e) { fileFullName = ""; } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { fileFullName = ""; } } } return fileFullName; } }
第二个类 NetUtil
[java]
view plain
copy
print?
package com.example.image_head;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class NetUtil {
// 一般来说用一个生成一个UUID的话,会可靠很多,这里就不考虑这个了
// 而且一般来说上传文件最好用BASE64进行编码,你只要用BASE64不用的符号就可以保证不冲突了。
// 尤其是上传二进制文件时,其中很可能有\r、\n之类的控制字符,有时还可能出现最高位被错误处理的问题,所以必须进行编码。
public static final String BOUNDARY = "--my_boundary--";
/**
* 普通字符串数据
* @param textParams
* @param ds
* @throws Exception
*/
public static void writeStringParams(Map<String, String> textParams,
DataOutputStream ds) throws Exception {
Set<String> keySet = textParams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
String value = textParams.get(name);
ds.writeBytes("--" + BOUNDARY + "\r\n");
ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
ds.writeBytes("\r\n");
value = value + "\r\n";
ds.write(value.getBytes());
}
}
/**
* 文件数据
* @param fileparams
* @param ds
* @throws Exception
*/
public static void writeFileParams(Map<String, File> fileparams,
DataOutputStream ds) throws Exception {
Set<String> keySet = fileparams.keySet();
for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
String name = it.next();
File value = fileparams.get(name);
ds.writeBytes("--" + BOUNDARY + "\r\n");
//uploadedfile与服务器端内容匹配
ds.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\""
+ URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n");
ds.writeBytes("Content-Type:application/octet-stream \r\n");
ds.writeBytes("\r\n");
ds.write(getBytes(value));
ds.writeBytes("\r\n");
}
}
// 把文件转换成字节数组
private static byte[] getBytes(File f) throws Exception {
FileInputStream in = new FileInputStream(f);
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = in.read(b)) != -1) {
out.write(b, 0, n);
}
in.close();
return out.toByteArray();
}
/**
* 添加结尾数据
* @param ds
* @throws Exception
*/
public static void paramsEnd(DataOutputStream ds) throws Exception {
ds.writeBytes("--" + BOUNDARY + "--" + "\r\n");
ds.writeBytes("\r\n");
}
public static String readString(InputStream is) {
return new String(readBytes(is));
}
public static byte[] readBytes(InputStream is) {
try {
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((len = is.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
baos.close();
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
package com.example.image_head; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.net.URLEncoder; import java.util.Iterator; import java.util.Map; import java.util.Set; public class NetUtil { // 一般来说用一个生成一个UUID的话,会可靠很多,这里就不考虑这个了 // 而且一般来说上传文件最好用BASE64进行编码,你只要用BASE64不用的符号就可以保证不冲突了。 // 尤其是上传二进制文件时,其中很可能有\r、\n之类的控制字符,有时还可能出现最高位被错误处理的问题,所以必须进行编码。 public static final String BOUNDARY = "--my_boundary--"; /** * 普通字符串数据 * @param textParams * @param ds * @throws Exception */ public static void writeStringParams(Map<String, String> textParams, DataOutputStream ds) throws Exception { Set<String> keySet = textParams.keySet(); for (Iterator<String> it = keySet.iterator(); it.hasNext();) { String name = it.next(); String value = textParams.get(name); ds.writeBytes("--" + BOUNDARY + "\r\n"); ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n"); ds.writeBytes("\r\n"); value = value + "\r\n"; ds.write(value.getBytes()); } } /** * 文件数据 * @param fileparams * @param ds * @throws Exception */ public static void writeFileParams(Map<String, File> fileparams, DataOutputStream ds) throws Exception { Set<String> keySet = fileparams.keySet(); for (Iterator<String> it = keySet.iterator(); it.hasNext();) { String name = it.next(); File value = fileparams.get(name); ds.writeBytes("--" + BOUNDARY + "\r\n"); //uploadedfile与服务器端内容匹配 ds.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + URLEncoder.encode(value.getName(), "UTF-8") + "\"\r\n"); ds.writeBytes("Content-Type:application/octet-stream \r\n"); ds.writeBytes("\r\n"); ds.write(getBytes(value)); ds.writeBytes("\r\n"); } } // 把文件转换成字节数组 private static byte[] getBytes(File f) throws Exception { FileInputStream in = new FileInputStream(f); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int n; while ((n = in.read(b)) != -1) { out.write(b, 0, n); } in.close(); return out.toByteArray(); } /** * 添加结尾数据 * @param ds * @throws Exception */ public static void paramsEnd(DataOutputStream ds) throws Exception { ds.writeBytes("--" + BOUNDARY + "--" + "\r\n"); ds.writeBytes("\r\n"); } public static String readString(InputStream is) { return new String(readBytes(is)); } public static byte[] readBytes(InputStream is) { try { byte[] buffer = new byte[1024]; int len = -1; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } baos.close(); return baos.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } }
方法,在button的点击事件中添加线程
[java]
view plain
copy
print?
new Thread(uploadImageRunnable).start();
new Thread(uploadImageRunnable).start();
[java]
view plain
copy
print?
Runnable uploadImageRunnable = new Runnable() {
@Override
public void run() {
if(TextUtils.isEmpty(imgUrl)){//php服务器端url
Toast.makeText(getActivity(), "还没有设置上传服务器的路径!", Toast.LENGTH_SHORT).show();
return;
}
Map<String, String> textParams = new HashMap<String, String>();
Map<String, File> fileparams = new HashMap<String, File>();
try {
// 创建一个URL对象
URL url = new URL(imgUrl);
textParams = new HashMap<String, String>();
fileparams = new HashMap<String, File>();
// 要上传的图片文件
File file = new File(urlpath);//本地图片路径
fileparams.put("image", file);
// 利用HttpURLConnection对象从网络中获取网页数据
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置连接超时(记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作)
conn.setConnectTimeout(5000);
// 设置允许输出(发送POST请求必须设置允许输出)
conn.setDoOutput(true);
// 设置使用POST的方式发送
conn.setRequestMethod("POST");
// 设置不使用缓存(容易出现问题)
conn.setUseCaches(false);
conn.setRequestProperty("Charset", "UTF-8");//设置编码
// 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头
conn.setRequestProperty("ser-Agent", "Fiddler");
// 设置contentType
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY);
OutputStream os = conn.getOutputStream();
DataOutputStream ds = new DataOutputStream(os);
NetUtil.writeStringParams(textParams, ds);
NetUtil.writeFileParams(fileparams, ds);
NetUtil.paramsEnd(ds);
// 对文件流操作完,要记得及时关闭
os.close();
// 服务器返回的响应吗
int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来
// 对响应码进行判断
if (code == 200) {// 返回的响应码200,是成功
// 得到网络返回的输入流
InputStream is = conn.getInputStream();
resultStr = NetUtil.readString(is);
} else {
Toast.makeText(getActivity(), "请求URL失败!", Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
};
Runnable uploadImageRunnable = new Runnable() { @Override public void run() { if(TextUtils.isEmpty(imgUrl)){//php服务器端url Toast.makeText(getActivity(), "还没有设置上传服务器的路径!", Toast.LENGTH_SHORT).show(); return; } Map<String, String> textParams = new HashMap<String, String>(); Map<String, File> fileparams = new HashMap<String, File>(); try { // 创建一个URL对象 URL url = new URL(imgUrl); textParams = new HashMap<String, String>(); fileparams = new HashMap<String, File>(); // 要上传的图片文件 File file = new File(urlpath);//本地图片路径 fileparams.put("image", file); // 利用HttpURLConnection对象从网络中获取网页数据 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // 设置连接超时(记得设置连接超时,如果网络不好,Android系统在超过默认时间会收回资源中断操作) conn.setConnectTimeout(5000); // 设置允许输出(发送POST请求必须设置允许输出) conn.setDoOutput(true); // 设置使用POST的方式发送 conn.setRequestMethod("POST"); // 设置不使用缓存(容易出现问题) conn.setUseCaches(false); conn.setRequestProperty("Charset", "UTF-8");//设置编码 // 在开始用HttpURLConnection对象的setRequestProperty()设置,就是生成HTML文件头 conn.setRequestProperty("ser-Agent", "Fiddler"); // 设置contentType conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + NetUtil.BOUNDARY); OutputStream os = conn.getOutputStream(); DataOutputStream ds = new DataOutputStream(os); NetUtil.writeStringParams(textParams, ds); NetUtil.writeFileParams(fileparams, ds); NetUtil.paramsEnd(ds); // 对文件流操作完,要记得及时关闭 os.close(); // 服务器返回的响应吗 int code = conn.getResponseCode(); // 从Internet获取网页,发送请求,将网页以流的形式读回来 // 对响应码进行判断 if (code == 200) {// 返回的响应码200,是成功 // 得到网络返回的输入流 InputStream is = conn.getInputStream(); resultStr = NetUtil.readString(is); } else { Toast.makeText(getActivity(), "请求URL失败!", Toast.LENGTH_SHORT).show(); } } catch (Exception e) { e.printStackTrace(); } handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler } };
[java]
view plain
copy
print?
</pre><div class="dp-highlighter bg_java"><div class="bar"><div class="tools"><strong>[java]</strong> <a target=_blank title="view plain" class="ViewSource" href="http://blog.csdn.net/xbw12138/article/details/50890255#">view plain</a><span data-mod="popu_168"> <a target=_blank title="copy" class="CopyToClipboard" href="http://blog.csdn.net/xbw12138/article/details/50890255#">copy</a></span><div style="left: 421px; top: 5638px; width: 18px; height: 18px; position: absolute; z-index: 99;"></div><span data-mod="popu_169"> <a target=_blank title="print" class="PrintSource" href="http://blog.csdn.net/xbw12138/article/details/50890255#">print</a></span><a target=_blank title="?" class="About" href="http://blog.csdn.net/xbw12138/article/details/50890255#">?</a><span class="tracking-ad" data-mod="popu_167"><a target=_blank title="在CODE上查看代码片" style="text-indent:0;" href="https://code.csdn.net/snippets/1610066" target="_blank"><img width="12" height="12" style="position:relative;top:1px;left:2px;" alt="在CODE上查看代码片" src="https://oscdn.geek-share.com/Uploads/Images/Content/201611/a7c8e286f463007e2a900848b93dd72c.png" /></a></span><span class="tracking-ad" data-mod="popu_170"><a target=_blank title="派生到我的代码片" style="text-indent:0;" href="https://code.csdn.net/snippets/1610066/fork" target="_blank"><img width="12" height="12" style="position:relative;top:2px;left:2px;" alt="派生到我的代码片" src="https://oscdn.geek-share.com/Uploads/Images/Content/201611/9e12f1d3e499fc949c886e7c9e0484f9" /></a></span></div></div><ol class="dp-j"><li class="alt"><span><span>Handler handler = </span><span class="keyword">new</span><span> Handler(</span><span class="keyword">new</span><span> Handler.Callback() { </span></span></li><li><span> <span class="annotation">@Override</span><span> </span></span></li><li class="alt"><span> <span class="keyword">public</span><span> </span><span class="keyword">boolean</span><span> handleMessage(Message msg) { </span></span></li><li><span> <span class="keyword">switch</span><span> (msg.what) { </span></span></li><li class="alt"><span> <span class="keyword">case</span><span> </span><span class="number">0</span><span>: </span></span></li><li><span> <span class="comment">//dialogs.dismiss();</span><span> </span></span></li><li class="alt"><span> <span class="keyword">try</span><span> { </span></span></li><li><span> <span class="comment">// 返回数据示例,根据需求和后台数据灵活处理</span><span> </span></span></li><li class="alt"><span> </span></li><li><span> JSONObject jsonObject = <span class="keyword">new</span><span> JSONObject(resultStr); </span></span></li><li class="alt"><span> String imageUrl = jsonObject.optString(<span class="string">"imageUrl"</span><span>); </span></span></li><li><span> Toast.makeText(getActivity(), imageUrl, Toast.LENGTH_SHORT).show(); </span></li><li class="alt"><span> }<span class="keyword">else</span><span>{ </span></span></li><li><span> Toast.makeText(getActivity(), jsonObject.optString(<span class="string">"statusMessage"</span><span>), Toast.LENGTH_SHORT).show(); </span></span></li><li class="alt"><span> } </span></li><li><span> </span></li><li class="alt"><span> } <span class="keyword">catch</span><span> (JSONException e) { </span></span></li><li><span> e.printStackTrace(); </span></li><li class="alt"><span> } </span></li><li><span> </span></li><li class="alt"><span> <span class="keyword">break</span><span>; </span></span></li><li><span> </span></li><li class="alt"><span> <span class="keyword">default</span><span>: </span></span></li><li><span> <span class="keyword">break</span><span>; </span></span></li><li class="alt"><span> } </span></li><li><span> <span class="keyword">return</span><span> </span><span class="keyword">false</span><span>; </span></span></li><li class="alt"><span> } </span></li><li><span> }); </span></li></ol><div class="save_code tracking-ad" style="display: none;" data-mod="popu_249"><a target=_blank target="_blank"><img src="https://oscdn.geek-share.com/Uploads/Images/Content/201701/9cc493f1e15b23d0f4eaea0d0f8b35d0.png" alt="" /></a></div></div><pre class="java" style="display: none;" name="code" code_snippet_id="1610066" snippet_file_name="blog_20160314_6_9143161">Handler handler = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { switch (msg.what) { case 0: //dialogs.dismiss(); try { // 返回数据示例,根据需求和后台数据灵活处理 JSONObject jsonObject = new JSONObject(resultStr); String imageUrl = jsonObject.optString("imageUrl"); Toast.makeText(getActivity(), imageUrl, Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getActivity(), jsonObject.optString("statusMessage"), Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); } break; default: break; } return false; } });
这样就好了
第二种。
在button监听事件中添加
[java]
view plain
copy
print?
new Task().execute();
new Task().execute();
[java]
view plain
copy
print?
class Task extends AsyncTask<String, Integer, Integer> {
@Override
protected Integer doInBackground(String... strings) {
Integer result = -1;
try {
result = UpFile.post(config_a.uploadUrl,
new File("/storage/extSdCard/b.png"));//本地图片路径
}
catch (IOException e) {
e.printStackTrace();
}
return result;
}
@Override
protected void onPostExecute(Integer result) {
Toast.makeText(getActivity(), "" + result, Toast.LENGTH_LONG).show();
}
}
class Task extends AsyncTask<String, Integer, Integer> { @Override protected Integer doInBackground(String... strings) { Integer result = -1; try { result = UpFile.post(config_a.uploadUrl, new File("/storage/extSdCard/b.png"));//本地图片路径 } catch (IOException e) { e.printStackTrace(); } return result; } @Override protected void onPostExecute(Integer result) { Toast.makeText(getActivity(), "" + result, Toast.LENGTH_LONG).show(); } }
Upload_image.java类
[java]
view plain
copy
print?
package com.example.image_head;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;
import com.example.configs.config_a;
import android.widget.Toast;
public class Upload_image {
public static class UpFile {
public static int post(String actionUrl, File file) throws IOException {
//产生随机分隔内容
String BOUNDARY = UUID.randomUUID().toString();
String PREFIX = "--";
String LINEND = "\r\n";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL url = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
//设置超时时间单位是毫秒
conn.setReadTimeout(5 * 1000);
//设置允许输入
conn.setDoInput(true);
//设置允许输出
conn.setDoOutput(true);
//不允许使用缓存
conn.setUseCaches(false);
//设置请求的方法为Post
conn.setRequestMethod("POST");
//设置维持长连接
conn.setRequestProperty("Connection", "keep-alive");
//设置字符集为UTF-8
conn.setRequestProperty("Charset", CHARSET);
//设置文件的类型
conn.setRequestProperty("Content-type", MULTIPART_FROM_DATA + "; boundary=" + BOUNDARY);
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
//发送文件数据
if (file != null) {
StringBuilder sb = new StringBuilder();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
//uploadedfile与服务器端内容匹配
sb.append("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + file.getName() + "\"" + LINEND);
//
sb.append("Content-Type: image/png" + LINEND);
sb.append(LINEND);
//写入输出流中
outStream.write(sb.toString().getBytes());
//将文件读入输入流中
InputStream is = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = -1;
//写入输出流中
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
//添加换行标识
outStream.write(LINEND.getBytes());
}
byte[] endData = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(endData);
//发送数据
outStream.flush();
//获取响应码 上传成功返回的是200
int res = conn.getResponseCode();
return res;
}
}
}
package com.example.image_head; import java.io.BufferedReader; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.UUID; import com.example.configs.config_a; import android.widget.Toast; public class Upload_image { public static class UpFile { public static int post(String actionUrl, File file) throws IOException { //产生随机分隔内容 String BOUNDARY = UUID.randomUUID().toString(); String PREFIX = "--"; String LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL url = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); //设置超时时间单位是毫秒 conn.setReadTimeout(5 * 1000); //设置允许输入 conn.setDoInput(true); //设置允许输出 conn.setDoOutput(true); //不允许使用缓存 conn.setUseCaches(false); //设置请求的方法为Post conn.setRequestMethod("POST"); //设置维持长连接 conn.setRequestProperty("Connection", "keep-alive"); //设置字符集为UTF-8 conn.setRequestProperty("Charset", CHARSET); //设置文件的类型 conn.setRequestProperty("Content-type", MULTIPART_FROM_DATA + "; boundary=" + BOUNDARY); DataOutputStream outStream = new DataOutputStream(conn.getOutputStream()); //发送文件数据 if (file != null) { StringBuilder sb = new StringBuilder(); sb.append(PREFIX); sb.append(BOUNDARY); sb.append(LINEND); //uploadedfile与服务器端内容匹配 sb.append("Content-Disposition: form-data; name=\"uploadedfile\"; filename=\"" + file.getName() + "\"" + LINEND); // sb.append("Content-Type: image/png" + LINEND); sb.append(LINEND); //写入输出流中 outStream.write(sb.toString().getBytes()); //将文件读入输入流中 InputStream is = new FileInputStream(file); byte[] buffer = new byte[1024]; int len = -1; //写入输出流中 while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); //添加换行标识 outStream.write(LINEND.getBytes()); } byte[] endData = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(endData); //发送数据 outStream.flush(); //获取响应码 上传成功返回的是200 int res = conn.getResponseCode(); return res; } } }
这样也能成功,
相关文章推荐
- android客户端加载网络大图片如何避免内存溢出的两种方法
- 两种android客户端传图片的方法
- 阿冰教你一步一步做Android新闻客户端(二)两种异步线程加载图片的方法
- android 图片叠加效果——两种方法
- android客户端下载图片的方法
- Android 两种制作圆形/圆角图片的方法
- Android互联网访问图片并在客户端显示的方法
- Android从Camera中获取图片的两种方法
- android 图片叠加效果——两种方法的简介与内容
- Android:将数字画在图片上合成一张图的两种实现方法(一)
- 客户端Android和Webservice之间的图片文件传输解决方法
- Android从Camera中获取图片的两种方法
- Android实现图片轮播效果的两种方法
- android两种使用照相功能获取图片的方法
- android显示图片的两种方法
- android两种使用照相功能获取图片的方法
- 2012-7-20 android 图片叠加效果——两种方法
- 【Android】Web开发之显示网络图片的两种方法
- android 改变背景图片的两种方法
- android 图片叠加效果——两种方法