android表单上传
❶ android中数据上传到服务器怎么实现
服务器端写个servlet,然后在doPost()方法里处理客户端上传的文件,大概代码: DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024 * 1024); // 设置最多只允许在内存中存储的数据, 单位:字节 factory.setRepository(cachepath); // 设置一旦文件大小超过设定值时数据存放的目录 ServletFileUpload srvFileUpload = new ServletFileUpload(factory); srvFileUpload.setSizeMax(1024 * 1024 * 1024); // 设置允许用户上传文件大小, 单位:字节 // 开始读取上传信息 List fileItems = null; try { fileItems = srvFileUpload.parseRequest(request); } catch (Exception e) { System.out.println("获取上传信息。。。。。。失败"); } // 依次处理每个上传的文件 Iterator iter = fileItems.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // 忽略其他不是文件域的所有表单信息 if (!item.isFormField()) { // 取出文件域的所有表单信息 } else { // 取出不是文件域的所有表单信息 } }
❷ android端 file文件上传
我们做web开发的时候几乎都是通过一个表单来实现上传。并且是post的方式。而且都必须要加个参数enctype = "multipart/form-data".然后再上传后台用各种框架里的插件之类的就可以接收了,并没有关心过这个文件具体是怎么传的。现在用android开发 没有那些框架了,所以不得不关心一下了。
其实我们这种前后台的交互是用的HTTP协议。而http协议默认是传的字符串。所以我们上传文件的话要加enctype = "multipart/form-data"这个参数来说明我们这传的是文件不是字符串了。而我们做web开发的时候,浏览器是自动解析HTTP协议的。里面传的哪些东西我们不用管。只要记住几个参数就行。而我们要上传的文件报文是保存在请求的头文件里面的。下面就是上传文件头文件的格式:
POST/logsys/home/uploadIspeedLog!doDefault.html HTTP/1.1
Accept: text/plain, */*
Accept-Language: zh-cn
Host: 192.168.24.56
Content-Type:multipart/form-data;boundary=-----------------------------7db372eb000e2
User-Agent: WinHttpClient
Content-Length: 3693
Connection: Keep-Alive
-------------------------------7db372eb000e2
Content-Disposition: form-data; name="file"; filename="kn.jpg"
Content-Type: image/jpeg
(此处省略jpeg文件二进制数据...)
-------------------------------7db372eb000e2--
这就是Http上传发送的文件格式。而我们要发送的时候必然要遵循这种格式来并且不能出一点差错包括每行后面的回车,下面一段文字是网上找的感觉写的比较精彩。(尊重原创:原文地址)
红色字体部分就是协议的头。给服务器上传数据时,并非协议头每个字段都得说明,其中,content-type是必须的,它包括一个类似标志性质的名为boundary的标志,它可以是随便输入的字符串。对后面的具体内容也是必须的。它用来分辨一段内容的开始。Content-Length: 3693 ,这里的3693是要上传文件的总长度。绿色字体部分就是需要上传的数据,可以是文本,也可以是图片等。数据内容前面需要有Content-Disposition, Content-Type以及Content-Transfer-Encoding等说明字段。最后的紫色部分就是协议的结尾了。
注意这一行:
Content-Type: multipart/form-data; boundary=---------------------------7db372eb000e2
根据 rfc1867, multipart/form-data是必须的.
---------------------------7db372eb000e2 是分隔符,分隔多个文件、表单项。其中b372eb000e2 是即时生成的一个数字,用以确保整个分隔符不会在文件或表单项的内容中出现。Form每个部分用分隔符分割,分隔符之前必须加上"--"着两个字符(即--{boundary})才能被http协议认为是Form的分隔符,表示结束的话用在正确的分隔符后面添加"--"表示结束。
前面的 ---------------------------7d 是 IE 特有的标志,Mozila 为---------------------------71.
每个分隔的数据的都可以用Content-Type来表示下面数据的类型,可以参考rfc1341
❸ Android中使用HttpPost实现数据与文件同时上传的功能
第一步:编写一个Servlet,把接收到的HTTP信息保存在一个文件中,代码如下:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//获取输入流,是HTTP协议中的实体内容
ServletInputStream sis=request.getInputStream();
//缓冲区
byte buffer[]=new byte[1024];
FileOutputStream fos=new FileOutputStream("d://file.log");
int len=sis.read(buffer, 0, 1024);
//把流里的信息循环读入到file.log文件中
while( len!=-1 )
{
fos.write(buffer, 0, len);
len=sis.readLine(buffer, 0, 1024);
}
fos.close();
sis.close();
}
第二步:实现如下图1的的表单页面,生成一个注册表单,提交到Servlet中
详细的代码如下:
<form action="servlet/ReceiveFile" method="post" enctype="multipart/form-data">
第一个参数<input type="text" name="name1"/> <br/>
第二个参数<input type="text" name="name2"/> <br/>
第一个上传的文件<input type="file" name="file1"/> <br/>
第二个上传的文件<input type="file" name="file2"/> <br/>
<input type="submit" value="提交">
</form>
注意了,由于要上传附件,所以一定要设置enctype为multipart/form-data,才可以实现附件的上传。
第三步:填写完信息后按“提交”按钮后,在D盘下查找file.log文件用记事本打开,数据如下:
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="name1"
hello
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="name2"
world
-----------------------------7d92221b604bc
Content-Disposition: form-data; name="file1"; filename="C:/2.GIF"
Content-Type: image/gif
GIF89a
❹ 安卓界面的按钮怎么提交事件,例如我要提交到一个java文件,实现注册的功能,跟HTML里的表单提交类似
首先你这个是布局文件,按钮你写了onclick事件,这个时候你应该在Activity应用这个布局文件,再在那个Activity获取你要的参数,然后直接调用你写的验证的java方法就OK了
❺ android如何实现图片批量上传
首先,以下架构下的批量文件上传可能会失败或者不会成功:
1.android客户端+springMVC服务端:服务端采用org.springframework.web.multipart.MultipartHttpServletRequest作为批量上传接收类,这种搭配下的批量文件上传会失败,最终服务端只会接受到一个文件,即只会接受到第一个文件。可能因为MultipartHttpServletRequest对servlet原本的HttpServletRequest类进行封装,导致批量上传有问题。
2.android客户端+strutsMVC服务端:
上传成功的方案:
采用android客户端+Servlet(HttpServletRequest)进行文件上传。
Servlet端代码如下:
[java] view plainprint?
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try
{
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext())
{
FileItem item = (FileItem) itr.next();
if (item.isFormField())
{
System.out.println("表单参数名:" + item.getFieldName() + ",表单参数值:" + item.getString("UTF-8"));
}
else
{
if (item.getName() != null && !item.getName().equals(""))
{
System.out.println("上传文件的大小:" + item.getSize());
System.out.println("上传文件的类型:" + item.getContentType());
// item.getName()返回上传文件在客户端的完整路径名称
System.out.println("上传文件的名称:" + item.getName());
File tempFile = new File(item.getName());
// 上传文件的保存路径
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上传文件成功!");
} else
{
request.setAttribute("upload.message", "没有选择上传文件!");
}
}
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
catch (Exception e)
{
e.printStackTrace();
request.setAttribute("upload.message", "上传文件失败!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
android端代码如下:
[java] view plainprint?
public class SocketHttpRequester {
/**
*多文件上传
* 直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
* <FORM METHOD=POST ACTION="http://192.168.1.101:8083/upload/servlet/UploadServlet" enctype="multipart/form-data">
<INPUT TYPE="text" NAME="name">
<INPUT TYPE="text" NAME="id">
<input type="file" name="imagefile"/>
<input type="file" name="zip"/>
</FORM>
* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.iteye.cn或http://192.168.1.101:8083这样的路径测试)
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static boolean post(String path, Map<String, String> params, FormFile[] files) throws Exception{
final String BOUNDARY = "---------------------------7da2137580612"; //数据分隔线
final String endline = "--" + BOUNDARY + "--\r\n";//数据结束标志
int fileDataLength = 0;
for(FormFile uploadFile : files){//得到文件类型数据的总长度
StringBuilder fileExplain = new StringBuilder();
fileExplain.append("--");
fileExplain.append(BOUNDARY);
fileExplain.append("\r\n");
fileExplain.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileExplain.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
fileExplain.append("\r\n");
fileDataLength += fileExplain.length();
if(uploadFile.getInStream()!=null){
fileDataLength += uploadFile.getFile().length();
}else{
fileDataLength += uploadFile.getData().length;
}
}
StringBuilder textEntity = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {//构造文本类型参数的实体数据
textEntity.append("--");
textEntity.append(BOUNDARY);
textEntity.append("\r\n");
textEntity.append("Content-Disposition: form-data; name=\""+ entry.getKey() + "\"\r\n\r\n");
textEntity.append(entry.getValue());
textEntity.append("\r\n");
}
//计算传输给服务器的实体数据总长度
int dataLength = textEntity.toString().getBytes().length + fileDataLength + endline.getBytes().length;
URL url = new URL(path);
int port = url.getPort()==-1 ? 80 : url.getPort();
Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
OutputStream outStream = socket.getOutputStream();
//下面完成HTTP请求头的发送
String requestmethod = "POST "+ url.getPath()+" HTTP/1.1\r\n";
outStream.write(requestmethod.getBytes());
String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
outStream.write(accept.getBytes());
String language = "Accept-Language: zh-CN\r\n";
outStream.write(language.getBytes());
String contenttype = "Content-Type: multipart/form-data; boundary="+ BOUNDARY+ "\r\n";
outStream.write(contenttype.getBytes());
String contentlength = "Content-Length: "+ dataLength + "\r\n";
outStream.write(contentlength.getBytes());
String alive = "Connection: Keep-Alive\r\n";
outStream.write(alive.getBytes());
String host = "Host: "+ url.getHost() +":"+ port +"\r\n";
outStream.write(host.getBytes());
//写完HTTP请求头后根据HTTP协议再写一个回车换行
outStream.write("\r\n".getBytes());
//把所有文本类型的实体数据发送出来
outStream.write(textEntity.toString().getBytes());
//把所有文件类型的实体数据发送出来
for(FormFile uploadFile : files){
StringBuilder fileEntity = new StringBuilder();
fileEntity.append("--");
fileEntity.append(BOUNDARY);
fileEntity.append("\r\n");
fileEntity.append("Content-Disposition: form-data;name=\""+ uploadFile.getParameterName()+"\";filename=\""+ uploadFile.getFilname() + "\"\r\n");
fileEntity.append("Content-Type: "+ uploadFile.getContentType()+"\r\n\r\n");
outStream.write(fileEntity.toString().getBytes());
if(uploadFile.getInStream()!=null){
byte[] buffer = new byte[1024];
int len = 0;
while((len = uploadFile.getInStream().read(buffer, 0, 1024))!=-1){
outStream.write(buffer, 0, len);
}
uploadFile.getInStream().close();
}else{
outStream.write(uploadFile.getData(), 0, uploadFile.getData().length);
}
outStream.write("\r\n".getBytes());
}
//下面发送数据结束标志,表示数据已经结束
outStream.write(endline.getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
return false;
}
outStream.flush();
outStream.close();
reader.close();
socket.close();
return true;
}
/**
*单文件上传
* 提交数据到服务器
* @param path 上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.itcast.cn或http://192.168.1.10:8080这样的路径测试)
* @param params 请求参数 key为参数名,value为参数值
* @param file 上传文件
*/
public static boolean post(String path, Map<String, String> params, FormFile file) throws Exception{
return post(path, params, new FormFile[]{file});
}
}
❻ android 向服务器post多个文件的时候,服务器报异常
struts 用的是fileupload 这个组件
默认的文件上传表单最大值是2M,超过了会抛出异常
如果是struts的话,要配置一下文件上传的最大值
在struts.xml中加入 <constant name="struts.multipart.maxSize" value="10485760"/>
10MB
❼ android平板 怎么设计好看的表单
1.来说下主程序MainActivity.java
public class MainActivity extends Activity {
private TableLayout table;
private Button select;
EmployeeDao = new EmployeeDao(this);
private Button add;
private Button update;
int selectedRow = 0;
int ActivityID=1;
List<Employee> list = new ArrayList<Employee>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
table = (TableLayout) this.findViewById(R.id.table);
table.setBackgroundColor(Color.GREEN);
//table.set
add = (Button) this.findViewById(R.id.add);
update = (Button) this.findViewById(R.id.update);
select = (Button) this.findViewById(R.id.select);
// 点击查询按钮处理事件
// Toast.makeText(this, "已查询过了!", Toast.LENGTH_SHORT).show();
select.setOnClickListener(new selectListener());
// 点击添加按钮事件处理,跳转到另一个activity
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(MainActivity.this, AddAndUpdateActivity.class);
Bundle bundle=new Bundle();
ActivityID=1;
bundle.putInt("ID", ActivityID);
i.putExtras(bundle);
startActivity(i);
}
});
// 更新员工信息
update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setClass(MainActivity.this, AddAndUpdateActivity.class);
Bundle bundle=new Bundle();
ActivityID=2;
bundle.putInt("ID", ActivityID);
bundle.putInt("emID", selectedRow);
i.putExtras(bundle);
startActivity(i);
}
});
}
// 查询信息监听类
private class selectListener implements View.OnClickListener {
@Override
public void onClick(View v) {
list = .getAll();
if (list.size() != 0) {
for (int i = 0; i < list.size(); i++) {
TableRow row = new TableRow(MainActivity.this);
Employee em = list.get(i);// 查找所有员工信息
// 设置行标记
row.setId(em.getId());
row.setPadding(6, 1, 6, 1);
row.setGravity(Gravity.CENTER);
row.setBackgroundColor(Color.WHITE);
TextView view1 = new TextView(MainActivity.this);
view1.setText(Integer.toString(em.getId()));
view1.setGravity(Gravity.CENTER);//文本居中
view1.setTextSize((float) 18);文本大小
view1.setTextColor(Color.RED);
view1.setPadding(10, 2, 10, 2);//边框左、上、右、下
row.addView(view1);添加一行
TextView view2 = new TextView(MainActivity.this);
view2.setText(em.getName());
view2.setTextSize((float) 18);
view2.setPadding(10, 2, 10, 2);
row.addView(view2);
TextView view3 = new TextView(MainActivity.this);
view3.setText(Integer.toString(em.getAge()));
view3.setTextSize((float) 18);
view3.setGravity(Gravity.CENTER);
view3.setPadding(10, 2, 10, 2);
row.addView(view3);
TextView view4 = new TextView(MainActivity.this);
view4.setText(em.getPosition());
view4.setTextSize((float) 18);
view4.setPadding(10, 2, 10, 2);
row.addView(view4);
TextView view5 = new TextView(MainActivity.this);
view5.setText(em.getDepartment());
view5.setTextSize((float) 18);
view5.setPadding(10, 2, 10, 2);
row.addView(view5);
TextView view6 = new TextView(MainActivity.this);
view6.setText(em.getWorkdate());
view6.setTextSize((float) 18);
view6.setPadding(10, 2, 10, 2);
row.addView(view6);
TextView view7 = new TextView(MainActivity.this);
SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
Date date = null;
try {
date = format.parse(em.getWorkdate());
} catch (ParseException e) {
e.printStackTrace();
}
float d= (float)((new Date().getTime()-date.getTime())/(24*60*60*1000)/365);//计算工龄
String dd=Integer.toString((int) d+1);
view7.setText(dd);
view7.setTextSize((float) 18);
view7.setPadding(10, 2, 10, 2);
row.addView(view7);
table.addView(row);
row.setOnClickListener(new View.OnClickListener() {//点击某行触发事件
@Override
public void onClick(View v) {
System.out.println("行标记:" + v.getId());
for (int i = 0; i < table.getChildCount(); i++) {
if (table.getChildAt(i).getId() != v.getId())
table.getChildAt(i).setBackgroundColor(Color.WHITE);
// 选中时,高亮显示即设置背景色
v.setBackgroundColor(Color.YELLOW);
}
selectedRow = v.getId();
AlertDialog.Builder dialog = new AlertDialog.Builder(
MainActivity.this);
dialog.setTitle("请确认:");
dialog.setMessage("是否删除这条记录?");
dialog.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(
DialogInterface dialog,int which) {
EmployeeDao = new EmployeeDao(MainActivity.this);
.delete(selectedRow);
Toast.makeText(MainActivity.this,
"删除成功", Toast.LENGTH_SHORT).show();
Intent i = new Intent();
i.setClass(MainActivity.this,MainActivity.class);
startActivity(i);
}
});
dialog.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
} });
dialog.show();
}
});
}
}
}
}
}
2.然后是添加和更新的界面,两个功能使用同一个xml文件布局
<RelativeLayout
android:background="#2691f2"
tools:context=".AddAndUpdateActivity" >
<TextView
android:id="@+id/t"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:textSize="25sp"
android:text="@string/addinfo"
android:textColor="#bc4b86" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_below="@+id/t"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="30dp" />
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name" />
<EditText
android:id="@+id/nm"
android:inputType="text"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/age" />
<EditText
android:id="@+id/ag"
android:inputType="text"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/position" />
<EditText
android:id="@+id/pzs"
android:inputType="text"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/dptmt" />
<EditText
android:id="@+id/dptmt"
android:inputType="text"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_marginLeft="25dp" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/date" />
<EditText
android:id="@+id/wkdt"
android:inputType="text"
android:layout_width="150dp"
android:layout_height="wrap_content" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="20dp" />
<Button
android:id="@+id/addnew"
android:layout_width="60dp"
android:layout_height="40dp"
android:layout_gravity="center_horizontal"
android:text="@string/add" >
</Button>
</LinearLayout>
</RelativeLayout>