Android檔案上傳至tomcat,服務端+用戶端範例程式碼

來源:互聯網
上載者:User


這個程式在tomcat 5.0伺服器環境下成功運行,程式簡單,運行效率非常高,非常給力的一個代碼,借鑒eoeandroid裡大手們的指點,由於本人在J2EE的開發非常不瞭解,下半年開學~所以jsp什麼的顯得那麼不得心應手,但是一些j2me的知識還是比較熟悉,這個程式非常簡單,注釋也非常給力~google了半天,感覺肯定會有許多和我一樣的菜鳥很需要的。所以貼上來與大家一起分享。 開發這個前一定要手動匯入幾個必備的jar檔案,比如 tomcat下的servlet-api.jar,commons-fileupload-1.2.jar否則無法編譯通過,整天開發j2me遇到這些j2ee,真的很不舒服,慢慢習慣就好了~!基本常識吧~貼的代碼用戶端沒改,個人習慣把uploadfile()這個方法改成了uploadfile(String url,String filepath)從eoe下的原檔案  挺好的:http://u.115.com/file/aqzz7pna#簡單,實用!研究了半天webDAV還有那個有名的開源項目slide,無語啊。到最後發現,這個在手機上運行起來效率實在是低下,主要是感覺我們的主要功能不是這個,所以暫時不研究webDAV了~~~不過這個真的是挺經典的一個東西~ ******************伺服器端*************************

package net.blogjava.mobile;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;import java.util.List;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileItemFactory;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class UploadServlet extends HttpServlet{protected void service(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{try{request.setCharacterEncoding("UTF-8"); // 設定處理請求參數的編碼格式response.setContentType("text/html;charset=UTF-8"); // 設定Content-Type欄位值PrintWriter out = response.getWriter();// 下面的代碼開始使用Commons-UploadFile組件處理上傳的檔案資料FileItemFactory factory = new DiskFileItemFactory(); // 建立FileItemFactory對象ServletFileUpload upload = new ServletFileUpload(factory);// 分析請求,並得到上傳檔案的FileItem對象List<FileItem> items = upload.parseRequest(request);// 從web.xml檔案中的參數中得到上傳檔案的路徑String uploadPath = "C:\\tomcat\\webapps\\webdav\\";File file = new File(uploadPath);if (!file.exists()){file.mkdir();}String filename = ""; // 上傳檔案儲存到伺服器的檔案名稱InputStream is = null; // 當前上傳檔案的InputStream對象// 迴圈處理上傳檔案for (FileItem item : items){// 處理普通的表單域if (item.isFormField()){if (item.getFieldName().equals("filename")){// 如果新檔案不為空白,將其儲存在filename中if (!item.getString().equals(""))filename = item.getString("UTF-8");}}// 處理上傳檔案else if (item.getName() != null && !item.getName().equals("")){// 從用戶端發送過來的上傳檔案路徑中截取檔案名稱filename = item.getName().substring(item.getName().lastIndexOf("\\") + 1);is = item.getInputStream(); // 得到上傳檔案的InputStream對象}}// 將路徑和上傳檔案名稱組合成完整的服務端路徑filename = uploadPath + filename;// 如果伺服器已經存在和上傳檔案同名的檔案,則輸出提示資訊if (new File(filename).exists()){new File(filename).delete();}// 開始上傳檔案if (!filename.equals("")){// 用FileOutputStream開啟服務端的上傳檔案FileOutputStream fos = new FileOutputStream(filename);byte[] buffer = new byte[8192]; // 每次讀8K位元組int count = 0;// 開始讀取上傳檔案的位元組,並將其輸出到服務端的上傳檔案輸出資料流中while ((count = is.read(buffer)) > 0){fos.write(buffer, 0, count); // 向服務端檔案寫入位元組流}fos.close(); // 關閉FileOutputStream對象is.close(); // InputStream對象out.println("檔案上傳成功!");}}catch (Exception e){}}}

********************用戶端*****************************

import java.io.BufferedReader;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.InputStream;import java.io.InputStreamReader;import java.net.HttpURLConnection;import java.net.URL;import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView;import android.widget.Toast;/* import相關class */public class EX08_11 extends Activity{/** 變數聲明 filename:上傳後在伺服器上的檔案名稱 uploadFile:要上傳的檔案路徑 actionUrl:伺服器上對應的程式路徑*/private String uploadFile = "/sdcard/notepad/txt/213.txt";private String srcPath = "/sdcard/notepad/txt/213.txt";private String actionUrl = "http://10.0.2.2:8080/upload_file_service/upload.jsp";private TextView mText1;private TextView mText2;private Button mButton;@Overridepublic void onCreate(Bundle savedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.main);mText1 = (TextView) findViewById(R.id.myText2);mText1.setText("檔案路徑:\n" + uploadFile);mText2 = (TextView) findViewById(R.id.myText3);mText2.setText("上傳網址:\n" + actionUrl);/* 設定mButton的onClick事件處理 */mButton = (Button) findViewById(R.id.myButton);mButton.setOnClickListener(new View.OnClickListener(){public void onClick(View v){uploadFile();}});}/* 上傳檔案至Server的方法 */private void uploadFile(){String uploadUrl = "http://10.0.2.2:8080/upload_file_service/UploadServlet";String end = "\r\n";String twoHyphens = "--";String boundary = "******";try{URL url = new URL(uploadUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();httpURLConnection.setDoInput(true);httpURLConnection.setDoOutput(true);httpURLConnection.setUseCaches(false);httpURLConnection.setRequestMethod("POST");httpURLConnection.setRequestProperty("Connection", "Keep-Alive");httpURLConnection.setRequestProperty("Charset", "UTF-8");httpURLConnection.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);DataOutputStream dos = new DataOutputStream(httpURLConnection.getOutputStream());dos.writeBytes(twoHyphens + boundary + end);dos.writeBytes("Content-Disposition: form-data; name=\"file\"; filename=\""+ srcPath.substring(srcPath.lastIndexOf("/") + 1)+ "\"" + end);dos.writeBytes(end);FileInputStream fis = new FileInputStream(srcPath);byte[] buffer = new byte[8192]; // 8kint count = 0;while ((count = fis.read(buffer)) != -1){dos.write(buffer, 0, count);}fis.close();dos.writeBytes(end);dos.writeBytes(twoHyphens + boundary + twoHyphens + end);dos.flush();InputStream is = httpURLConnection.getInputStream();InputStreamReader isr = new InputStreamReader(is, "utf-8");BufferedReader br = new BufferedReader(isr);String result = br.readLine();Toast.makeText(this, result, Toast.LENGTH_LONG).show();dos.close();is.close();} catch (Exception e){e.printStackTrace();setTitle(e.getMessage());}}} 


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.