安卓日记——利用http上传文件到服务器

时间:2022-01-26 04:01:27

利用安卓上传文件到服务器首先你要有服务器,第二你要有个处理上传文件的后台

建议自己先学习使用tomcat服务器自己想办法

可以用tomcat把自己电脑变为服务器(不过手机和电脑要在用一个局域网而且地址用cmd然后输入ipconfig找ipv4的,自己试试看吧)

我的后台采用jsp


下面是安卓源码

源码该备注的地方我都写好了,我也是借用别人写好的uploadutil,有兴趣可以研究,没兴趣的话会用就行

这个是mainactivity

package com.example.uploadpic;

import java.io.File;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener{
private static final String TAG = "uploadImage";
//这里写自己服务器后台的地址,后台源码会附上
private static String requestURL = "http://119.29.136.149:8080/upload.jsp";
private Button selectImage,uploadImage;
private ImageView imageView;

private String picPath = null;

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

setContentView(R.layout.activity_main);

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(final View v) {
switch (v.getId()) {
case R.id.selectImage:
/***
* 打开选择图片的工具
* 想上传其他类型文件的用第三方文件浏览器
*/
final Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 1);
break;
case R.id.uploadImage:
final File file = new File(picPath);
if(file!=null)
{

//final String request = UploadUtil.uploadFile( file, requestURL);
new AsyncTask<Void, Void, String>(){

@Override
protected String doInBackground(Void... arg0) {
// TODO Auto-generated method stub
final String request = UploadUtil.uploadFile( file, requestURL);
return request;
}

protected void onPostExecute(String result) {

uploadImage.setText(result);
};
}.execute();

}
break;
default:
break;
}
}

@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
if(resultCode==Activity.RESULT_OK)
{
final Uri uri = data.getData();
Log.e(TAG, "uri = "+ uri);

final String[] pojo = {MediaStore.Images.Media.DATA};

final Cursor cursor = managedQuery(uri, pojo, null, null,null);
if(cursor!=null)
{
final ContentResolver cr = this.getContentResolver();
final int colunm_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
final String path = cursor.getString(colunm_index);
picPath = path;
}
}

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

}
下面是uploadutil

package com.example.uploadpic;

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.UUID;

import android.util.Log;

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

try {
final URL url = new URL(RequestURL);
final 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)
{
/**
* 当文件不为空,把文件包装并且上传
*/
final DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
final StringBuffer sb = new StringBuffer();
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINE_END);
/**
* 这里重点注意:
* name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/

sb.append("Content-Disposition: form-data; name=\"img\"; 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());
final InputStream is = new FileInputStream(file);
final 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());
final byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
dos.write(end_data);
dos.flush();
/**
* 获取响应码 200=成功
* 当响应成功,获取响应的流
*/
final int res = conn.getResponseCode();
Log.e(TAG, "response code:"+res);
if(res==200)
{
Log.e(TAG, "request success");
final InputStream input = conn.getInputStream();
final 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 (final MalformedURLException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
return result;
}
}

下面是服务器jsp要用到两个库(commons-io-1.4.jar和commons-fileupload-1.2.1.jar)

我已经把服务器端的东西和安卓源码打包好(直接把upload文件夹拷贝到tomcat的webapps里就好,不知道我说什么的建议先去学习使用tomcat)

<%@ page language="java" pageEncoding="utf-8"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.net.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.fileupload.FileUploadBase.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>


<%
String fileName=null;
String t_ext=null;
String save_path=null;
final long MAX_SIZE=5*1024*1024;
String filepath=null;

FileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload servletFileUpload =new ServletFileUpload(factory);
servletFileUpload.setHeaderEncoding("UTF-8");
servletFileUpload.setSizeMax(MAX_SIZE);

List<FileItem>fileItemsList =servletFileUpload.parseRequest(request);
if (fileItemsList!=null && fileItemsList.size()!=0) {
Iterator fileItr =fileItemsList.iterator();
while(fileItr.hasNext()){
FileItem item =(FileItem)fileItr.next();
if(item!=null && !item.isFormField()){
fileName=item.getName();
long size=item.getSize();
if(!"".equals(fileName) && size!=0){
fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
t_ext=fileName.substring(fileName.lastIndexOf(".")+1);
//生成随机数名字
String save_name="file"+UUID.randomUUID().toString()+"."+t_ext;
filepath=save_name;
save_path="/upload/"+save_name;
File file=new File(request.getSession().getServletContext().getRealPath(save_path));
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}

item.write(file);
}

}
}

}
response.setCharacterEncoding("UTF-8");
response.setContentType("text/plain;charset=UTF-8");
java.io.PrintWriter p=response.getWriter();
// p.write("true");
p.write(filepath);
p.close();

%>

源码地址:https://github.com/jkgeekJack/UploadPic