android怎样上传图片到服务器

 我来答
手机用户885
推荐于2017-09-07 · TA获得超过1540个赞
知道小有建树答主
回答量:1326
采纳率:50%
帮助的人:501万
展开全部
界面很简单,点击 【选择图片】,从图库里选择图片,显示到下面的imageview里,点击上传,就会上传到指定的服务器

布局文件:

?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="选择图片"
android:id="@+id/selectImage"
/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="上传图片"
android:id="@+id/uploadImage"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
/>
</LinearLayout>

Upload Activity:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105

public class Upload extends Activity implements OnClickListener {
private static String requestURL = "http://192.168.1.212:8011/pd/upload/fileUpload.do";
private Button selectImage, uploadImage;
private ImageView imageView;

private String picPath = null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.upload);

selectImage = (Button) this.findViewById(R.id.selectImage);
uploadImage = (Button) this.findViewById(R.id.uploadImage);
selectImage.setOnClickListener(this);
uploadImage.setOnClickListener(this);

imageView = (ImageView) this.findViewById(R.id.imageView);

}

@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.selectImage:
/***
* 这个是调用android内置的intent,来过滤图片文件 ,同时也可以过滤其他的
*/
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
break;
case R.id.uploadImage:
if (picPath == null) {

Toast.makeText(Upload.this, "请选择图片!", 1000).show();
} else {
final File file = new File(picPath);

if (file != null) {
String request = UploadUtil.uploadFile(file, requestURL);
uploadImage.setText(request);
}
}
break;
default:
break;
}
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK) {
/**
* 当选择的图片不为空的话,在获取到图片的途径
*/
Uri uri = data.getData();
Log.e(TAG, "uri = " + uri);
try {
String[] pojo = { MediaStore.Images.Media.DATA };

Cursor cursor = managedQuery(uri, pojo, null, null, null);
if (cursor != null) {
ContentResolver cr = this.getContentResolver();
int colunm_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String path = cursor.getString(colunm_index);
/***
* 这里加这样一个判断主要是为了第三方的软件选择,比如:使用第三方的文件管理器的话,你选择的文件就不一定是图片了,
* 这样的话,我们判断文件的后缀名 如果是图片格式的话,那么才可以
*/
if (path.endsWith("jpg") || path.endsWith("png")) {
picPath = path;
Bitmap bitmap = BitmapFactory.decodeStream(cr
.openInputStream(uri));
imageView.setImageBitmap(bitmap);
} else {
alert();
}
} else {
alert();
}

} catch (Exception e) {
}
}

super.onActivityResult(requestCode, resultCode, data);
}

private void alert() {
Dialog dialog = new AlertDialog.Builder(this).setTitle("提示")
.setMessage("您选择的不是有效的图片")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
picPath = null;
}
}).create();
dialog.show();
}

}

这个才是重点 UploadUtil:
?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89

public class UploadUtil {
private static final String TAG = "uploadFile";
private static final int TIME_OUT = 10 * 1000; // 超时时间
private static final String CHARSET = "utf-8"; // 设置编码
/**
* 上传文件到服务器
* @param file 需要上传的文件
* @param RequestURL 请求的rul
* @return 返回响应的内容
*/
public static int uploadFile(File file, String RequestURL) {
int res=0;
String result = null;
String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
String PREFIX = "--", LINE_END = "\r\n";
String CONTENT_TYPE = "multipart/form-data"; // 内容类型

try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIME_OUT);
conn.setConnectTimeout(TIME_OUT);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="+ BOUNDARY);

if (file != null) {
/**
* 当文件不为空时执行上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名
*/

sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""
+ file.getName() + "\"" + LINE_END);
sb.append("Content-Type: application/octet-stream; charset="
+ CHARSET + LINE_END);
sb.append(LINE_END);
dos.write(sb.toString().getBytes());
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = is.read(bytes)) != -1) {
dos.write(bytes, 0, len);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
.getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
res = conn.getResponseCode();
Log.e(TAG, "response code:" + res);
if (res == 200) {
Log.e(TAG, "request success");
InputStream input = conn.getInputStream();
StringBuffer sb1 = new StringBuffer();
int ss;
while ((ss = input.read()) != -1) {
sb1.append((char) ss);
}
result = sb1.toString();
Log.e(TAG, "result : " + result);
} else {
Log.e(TAG, "request error");
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return res;
}
}
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
man0306
推荐于2017-10-03 · TA获得超过958个赞
知道小有建树答主
回答量:707
采纳率:33%
帮助的人:400万
展开全部
服务器servlet代码
publicvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

String temp=request.getSession().getServletContext().getRealPath("/")+"temp"; //临时目录
System.out.println("temp="+temp);
String loadpath=request.getSession().getServletContext().getRealPath("/")+"Image"; //上传文件存放目录
System.out.println("loadpath="+loadpath);
DiskFileUpload fu =new DiskFileUpload();
fu.setSizeMax(1*1024*1024); // 设置允许用户上传文件大小,单位:字节
fu.setSizeThreshold(4096); // 设置最多只允许在内存中存储的数据,单位:字节
fu.setRepositoryPath(temp); // 设置一旦文件大小超过getSizeThreshold()的值时数据存放在硬盘的目录

//开始读取上传信息
int index=0;
List fileItems =null;

try {
fileItems = fu.parseRequest(request);
System.out.println("fileItems="+fileItems);
} catch (Exception e) {
e.printStackTrace();
}

Iterator iter = fileItems.iterator(); // 依次处理每个上传的文件
while (iter.hasNext())
{
FileItem item = (FileItem)iter.next();// 忽略其他不是文件域的所有表单信息
if (!item.isFormField())
{
String name = item.getName();//获取上传文件名,包括路径
name=name.substring(name.lastIndexOf("\\")+1);//从全路径中提取文件名
long size = item.getSize();
if((name==null||name.equals("")) && size==0)
continue;
int point = name.indexOf(".");
name=(new Date()).getTime()+name.substring(point,name.length())+index;
index++;
File fNew=new File(loadpath, name);
try {
item.write(fNew);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
else//取出不是文件域的所有表单信息
{
String fieldvalue = item.getString();
//如果包含中文应写为:(转为UTF-8编码)
//String fieldvalue = new String(item.getString().getBytes(),"UTF-8");
}
}
String text1="11";
response.sendRedirect("result.jsp?text1="+ text1);
}

  android客户端代码
publicclass PhotoUpload extends Activity {
private String newName ="image.jpg";
private String uploadFile ="/sdcard/image.JPG";
private String actionUrl ="http://192.168.0.71:8086/HelloWord/myForm";
private TextView mText1;
private TextView mText2;
private Button mButton;
@Override
publicvoid onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_upload);
mText1 = (TextView) findViewById(R.id.myText2);
//"文件路径:\n"+
mText1.setText(uploadFile);
mText2 = (TextView) findViewById(R.id.myText3);
//"上传网址:\n"+
mText2.setText(actionUrl);
/* 设置mButton的onClick事件处理 */
mButton = (Button) findViewById(R.id.myButton);
mButton.setOnClickListener(new View.OnClickListener()
{
publicvoid onClick(View v)
{
uploadFile();
}
});
}
/* 上传文件至Server的方法 */
privatevoid uploadFile()
{
String end ="\r\n";
String twoHyphens ="--";
String boundary ="*****";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 允许Input、Output,不使用Cache */
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设置传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type",
"multipart/form-data;boundary="+boundary);
/* 设置DataOutputStream */
DataOutputStream ds =
new DataOutputStream(con.getOutputStream());
ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; "+
"name=\"file1\";filename=\""+
newName +"\""+ end);
ds.writeBytes(end);
/* 取得文件的FileInputStream */
FileInputStream fStream =new FileInputStream(uploadFile);
/* 设置每次写入1024bytes */
int bufferSize =1024;
byte[] buffer =newbyte[bufferSize];
int length =-1;
/* 从文件读取数据至缓冲区 */
while((length = fStream.read(buffer)) !=-1)
{
/* 将资料写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
ds.writeBytes(end);
ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response内容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) !=-1 )
{
b.append( (char)ch );
}
/* 将Response显示于Dialog */
showDialog("上传成功"+b.toString().trim());
/* 关闭DataOutputStream */
ds.close();
}
catch(Exception e)
{
showDialog("上传失败"+e);
}
}
/* 显示Dialog的method */
privatevoid showDialog(String mess)
{
new AlertDialog.Builder(PhotoUpload.this).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定",new DialogInterface.OnClickListener()
{
publicvoid onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
}
本回答被提问者和网友采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式