當前位置:首頁 » 安卓系統 » android表單上傳

android表單上傳

發布時間: 2023-06-11 15:35:12

❶ 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>

熱點內容
外網訪問黑群暉 發布:2025-02-08 05:45:59 瀏覽:559
中央存儲伺服器公司地址 發布:2025-02-08 05:38:48 瀏覽:821
伺服器如何查詢表空間的文件路徑 發布:2025-02-08 05:38:00 瀏覽:162
宏基4741g哪個配置好 發布:2025-02-08 05:37:56 瀏覽:810
混合料運輸車的配置是如何計算的 發布:2025-02-08 05:31:35 瀏覽:293
android紅包插件 發布:2025-02-08 05:31:34 瀏覽:365
ea伺服器怎麼連接 發布:2025-02-08 05:16:45 瀏覽:463
更加密更改 發布:2025-02-08 05:15:20 瀏覽:786
倉儲資源配置都需要開展哪些任務 發布:2025-02-08 05:13:51 瀏覽:676
探針資料庫 發布:2025-02-08 05:13:35 瀏覽:80