android文件传输协议
篇一:Android之使用Http协议实现文件上传功能
注意一般使用Http协议上传的文件都比较小,一般是小于2M
这里示例是上传一个小的MP3文件
1.主Activity:MainActivity.java
?
?
?
?
?
?
?
?
? public class MainActivity extends Activity { private static final String TAG = MainActivity; private EditText timelengthText; private EditText titleText; private EditText videoText; @Override public void onCreate(Bundle savedInstanceState)
?? {
?? super.onCreate(savedInstanceState);
?? setContentView(R.layout.main);
?? //提交上传按钮
?? Button button = (Button) this.findViewById(R.id.button);
?? timelengthText = (EditText) this.findViewById(R.id.timelength);?? videoText = (EditText) this.findViewById(R.id.video);
?? titleText = (EditText) this.findViewById(R.id.title);
?? button.setOnClickListener(new View.OnClickListener()
?? {
?? @Override
?? public void onClick(View v)
?? {
?? String title = titleText.getText().toString();
?? String timelength = timelengthText.getText().toString();?? Map
?? params.put(title, title);
?? params.put(timelength, timelength);
?? try
?? {
??//得到SDCard的目录
??File uploadFile = new
File(Environment.getExternalStorageDirectory(), videoText.getText().toString());??//上传音频文件
??FormFile formfile = new FormFile(02.mp3, uploadFile, video, audio/mpeg);
??
SocketHttpRequester.post(00:8080/videoweb/video/manage.do, params, formfile);
??Toast.makeText(MainActivity.this, R.string.success,
1).show();
?? }
?? catch (Exception e)
?? {
??Toast.makeText(MainActivity.this, R.string.error,
1).show();
??Log.e(TAG, e.toString());
?? }
?? }
??});
?? }
?? }
2.上传工具类,注意里面构造协议字符串需要根据不同的提交表单来处理
?? public class SocketHttpRequester
?? {
?? /**
??* 发送xml数据
??* @param path 请求地址
??* @param xml xml数据
??* @param encoding 编码
??* @return
??* @throws Exception
??*/
?? public static byte[] postXml(String path, String xml, String encoding) throws Exception{
??byte[] data =