安卓之上传文件,即HTTP提交表单
获取文件:
public void Init()
{
noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
adapter = new GridAdapter(this);
adapter.update1();
noScrollgridview.setAdapter(adapter);
noScrollgridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
InputMethodManager imm = ( InputMethodManager ) arg1.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE );
imm.hideSoftInputFromWindow( arg1.getApplicationWindowToken( ) , 0 );
if (arg2 == Bimp.bmp.size())
{
new PopupWindows(PublishedActivity.this, noScrollgridview);
}
else
{
Intent intent = new Intent(PublishedActivity.this,
PhotoActivity.class);
intent.putExtra("ID", arg2);
startActivity(intent);
}
}
});
activity_selectimg_send = (Button) findViewById(R.id.activity_selectimg_send);
activity_selectimg_send.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//showDialog("ddd");
StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
.permitNetwork().build());
List<String> list = new ArrayList<String>();
for (int i = 0; i < Bimp.drr.size(); i++)
{
String Str = Bimp.drr.get(i).substring(
Bimp.drr.get(i).lastIndexOf("/") + 1,
Bimp.drr.get(i).lastIndexOf("."));
list.add(FileUtils.SDPATH + Str + ".JPEG");
String path = Bimp.drr.get(i);
// showDialog(path);
// showDialog(getDataValue("_member_id"));
// showDialog(((TextView) findViewById(R.id.activity_selectxxx_send)).getText().toString());
String fileKey = "imgFile";
UploadUtil uploadUtil = UploadUtil.getInstance();;
uploadUtil.setOnUploadProcessListener(PublishedActivity.this); //设置监听器监听上传状态
Map<String, String> params = new HashMap<String, String>();
params.put("userid", getDataValue("_member_id"));
params.put("content", ((TextView) findViewById(R.id.activity_selectxxx_send)).getText().toString());
uploadUtil.uploadFile( path,fileKey, "http://shop.tminji.com/sns/SendAMessage",params);
//String x = ((TextView)v.findViewById(R.id.activity_selectxxx_send)).getText().toString();
//uploadFile(path);
}
// 高清的压缩图片全部就在 list 路径里面了
// 高清的压缩过的 bmp 对象 都在 Bimp.bmp里面
// 完成上传服务器后 .........
showDialog("发布成功^_^");
FileUtils.deleteDir();
// Intent intent = new Intent(PublishedActivity.this, MainActivity.class);
// Bundle bundle = new Bundle();
// /*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/
// bundle.putString("Name", "feng88724");
// /*把bundle对象assign给Intent*/
//
// intent.setClass(PublishedActivity.this, MainActivity.class);
// intent.putExtras(bundle);
// startActivity(intent);
Intent intentx = new Intent(PublishedActivity.this, MainActivity.class);
/* 通过Bundle对象存储需要传递的数据 */
Bundle bundle = new Bundle();
/*字符、字符串、布尔、字节数组、浮点数等等,都可以传*/
bundle.putString("Name", "feng88724");
/*把bundle对象assign给Intent*/
intentx.putExtras(bundle);
startActivity(intentx);
}});
}
上传文件
private void toUploadFile(File file, String fileKey, String RequestURL,
Map<String, String> param) {
String result = null;
requestTime= 0;
long requestTime = System.currentTimeMillis();
long responseTime = 0;
try {
URL url = new URL(RequestURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(readTimeOut);
conn.setConnectTimeout(connectTimeout);
conn.setDoInput(true); // 允许输入流
conn.setDoOutput(true); // 允许输出流
conn.setUseCaches(false); // 不允许使用缓存
conn.setRequestMethod("POST"); // 请求方式
conn.setRequestProperty("Charset", CHARSET); // 设置编码
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);
//conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
/**
* 当文件不为空,把文件包装并且上传
*/
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
StringBuffer sb = null;
String params = "";
/***
* 以下是用于上传参数
*/
if (param != null && param.size() > 0) {
Iterator<String> it = param.keySet().iterator();
while (it.hasNext()) {
sb = null;
sb = new StringBuffer();
String key = it.next();
String value = param.get(key);
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"").append(LINE_END).append(LINE_END);
sb.append(value).append(LINE_END);
params = sb.toString();
Log.i(TAG, key+"="+params+"##");
dos.write(params.getBytes());
//dos.flush();
}
}
sb = null;
params = null;
sb = new StringBuffer();
/**
* 这里重点注意: name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
* filename是文件的名字,包含后缀名的 比如:abc.png
*/
sb.append(PREFIX).append(BOUNDARY).append(LINE_END);
sb.append("Content-Disposition:form-data; name=\"" + fileKey
+ "\"; filename=\"" + file.getName() + "\"" + LINE_END);
sb.append("Content-Type:image/pjpeg" + LINE_END); // 这里配置的Content-type很重要的 ,用于服务器端辨别文件的类型的
sb.append(LINE_END);
params = sb.toString();
sb = null;
Log.i(TAG, file.getName()+"=" + params+"##");
dos.write(params.getBytes());
/**上传文件*/
InputStream is = new FileInputStream(file);
onUploadProcessListener.initUpload((int)file.length());
byte[] bytes = new byte[1024];
int len = 0;
int curLen = 0;
while ((len = is.read(bytes)) != -1) {
curLen += len;
dos.write(bytes, 0, len);
onUploadProcessListener.onUploadProcess(curLen);
}
is.close();
dos.write(LINE_END.getBytes());
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
dos.write(end_data);
dos.flush();
//dos.write(tempOutputStream.toByteArray());
/**
* 获取响应码 200=成功 当响应成功,获取响应的流
*/
int res = conn.getResponseCode();
responseTime = System.currentTimeMillis();
this.requestTime = (int) ((responseTime-requestTime)/1000);
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);
sendMessage(UPLOAD_SUCCESS_CODE, "上传结果:"
+ result);
return;
} else {
Log.e(TAG, "request error");
sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:code=" + res);
return;
}
} catch (MalformedURLException e) {
sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
} catch (IOException e) {
sendMessage(UPLOAD_SERVER_ERROR_CODE,"上传失败:error=" + e.getMessage());
e.printStackTrace();
return;
}
}
安卓之上传文件,即HTTP提交表单的更多相关文章
- Django---静态文件配置,post提交表单的csrf问题(日后细说),创建app子项目和分析其目录,ORM对象关系映射简介,Django操作orm(重点)
Django---静态文件配置,post提交表单的csrf问题(日后细说),创建app子项目和分析其目录,ORM对象关系映射简介,Django操作orm(重点) 一丶Django的静态文件配置 #we ...
- ssi-uploader上传图片插件,点击选择文件按钮自动提交表单解决办法
先介绍一下这款插件,然后再谈使用中可能遇到的问题 ssi-uploader是一个JQuery的图片上传插件,界面比较美观 github地址:https://github.com/ssbeefeater ...
- 关于php上传文件过大的表单回填
也许标题有点绕口,有点无法让人理解.请原谅博主,语文学的不好,都赖体育老师. 问题场景重现:在某次迭代中,接到这样一个需求:当新建或编辑一个Bug(包含附件以及其他字段)上传附件过大时,退回到编辑页面 ...
- ajax上传文件 基于jquery form表单上传文件
<script src="/static/js/jquery.js"></script><script> $("#reg-btn&qu ...
- JSP SMARTUPLOAD组件:上传文件时同时获取表单参数
原因很简单: 注意更改from 属性啊!否则为null! 因为你用jspsmartuploadsmart时post请求 的格式是multipart/form-data,即enctype="m ...
- Java工具之上传文件
4个代码 1.前端JSP 2.自定义异常类 3.文件上传抽象类 4.Servlet 1.JSP <%@ page contentType="text/html;charset=UTF- ...
- Java Web之上传文件
本篇文章你会学到 1. Apache FileUpload组件 2.上传文件保存的路径和名称问题 3.缓存大小和临时目录 4.控制文件上传的格式 先讲一个简单的例子,一个注册页面,有账号,邮箱,和头像 ...
- 利用ajaxSubmit()方法实现Form提交表单后回调
1. 背景 最近在工作中,需要实现网页端图片上传到FTP服务器的功能.上传文件是用Form表单提交数据的方法向后台传输文件流,在此遇到了一个问题:后台在处理完图片上传功能后,需要向前台回传是 ...
- 4 django系列之HTML通过form标签来同时提交表单内容与上传文件
preface 我们知道提交表单有2种方式,一种直接通过submit页面刷新方法来提交,另一种通过ajax异步局部刷新的方法提交,上回我们说了通过ajax来提交文件到后台,现在说说通过submit来提 ...
随机推荐
- [转] map/reduce
如果你读过Google的那篇大名鼎鼎的论文“MapReduce: Simplified Data Processing on Large Clusters”,你就能大概明白map/reduce的概念. ...
- springboot 解决 woff2、ttf 跨域无法解析问题
@Configuration public class CORSConfiguration extends WebMvcConfigurerAdapter { @Override public voi ...
- Java第三阶段学习(十一、Servlet基础、servlet中的方法、servlet的配置、ServletContext对象)
一.Servlet简介 1.什么是servlet: sun公司提供的一套规范(接口),用来处理客户端请求.响应给浏览器的动态资源.但servlet的实质就是java代码,通过java的API动态的向 ...
- 【AtCoder】AGC030
A - Poisonous Cookies 有毒还吃,有毒吧 #include <bits/stdc++.h> #define fi first #define se second #de ...
- springBoot事物
1.事物 只是需要一个注解即可 2.事物程序 package com.caojun.springboot; import org.springframework.beans.factory.annot ...
- Windows下安装Tensorflow(python3.6):记录过程
安装前的情况: 之前使用的都是python2.7,但是tensorflow不支持2.x版本,那只有基于在3.x版本进行安装了 前段时间,我安装VS2017的时候安装了python3.6于是想在此基础上 ...
- 009.MySQL-Keepalived搭配脚本03
vim /etc/keepalived/check_MySQL.sh #vim #!/bin/bash MYSQL=/usr/local/mysql/bin/mysql MYSQL_HOST=loca ...
- 【Ray Tracing The Next Week 超详解】 光线追踪2-4 Perlin noise
Preface 为了得到更好的纹理,很多人采用各种形式的柏林噪声(该命名来自于发明人 Ken Perlin) 柏林噪声是一种比较模糊的白噪声的东西:(引用书中一张图) 柏林噪声是用来生成一些看似杂乱 ...
- RabbitMQ for windows
一.搭建环境 Rabbit MQ 是建立在强大的Erlang OTP平台上,因此安装RabbitMQ之前要先安装Erlang. erlang:http://www.erlang.org/downloa ...
- Web Service(一):初识
1. 前言 cxf 在项目中应用好久了,一直没有写总结,现在补上. 由于cxf 属于Web Service的一个实现,所以先学习和总结一下Web Service,作为学习cxf的基础. 2. WebS ...