android上傳文件

服務段代碼: java


package com.younchen.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class Reciver extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public Reciver() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String temp = "E:\\upload\\temp";
		String loadPath = "E:\\upload";
		DiskFileItemFactory df = new DiskFileItemFactory();
		df.setSizeThreshold(2048 * 1024 * 1024);
		df.setRepository(new File(temp));
		ServletFileUpload sfu = new ServletFileUpload(df);

		sfu.setSizeMax(1024 * 1024 * 1024); // 設置容許用戶上傳文件大小,單位:字節

		// 開始讀取上傳信息
		int index = 0;
		List fileItems = null;

		try {
			fileItems = sfu.parseRequest(request);
			System.out.println("fileItems=" + fileItems);
		} catch (Exception e) {
			e.printStackTrace();
		}

		Iterator iter = fileItems.iterator(); // 依次處理每一個上傳的文件
		while (iter.hasNext()) {
			FileItem item = (FileItem) iter.next();// 忽略其餘不是文件域的全部表單信息
			if (!item.isFormField()) {
				String name = item.getName();// 獲取上傳文件名,包括路徑
				name = name.substring(name.lastIndexOf("\\") + 1);// 從全路徑中提取文件名
				long size = item.getSize();
				if ((name == null || name.equals("")) && size == 0)
					continue;
				int point = name.indexOf(".");
				name = (new Date()).getTime()
						+ name.substring(point, name.length()) + index;
				index++;
				File fNew = new File(loadPath, name);
				try {
					item.write(fNew);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else// 取出不是文件域的全部表單信息
			{
				// String fieldvalue = item.getString();
				// 若是包含中文應寫爲:(轉爲UTF-8編碼)
				 String fieldvalue = new
				 String(item.getString().getBytes(),"UTF-8");
			}
		}

	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


客戶端代碼: web

public void onBtnClick(View v) {
		new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// TODO Auto-generated method stub
				String url = "http://***.***.*.***:8080/webproject/Reciver";
				WebUtil.uploadFile(url, "wugui.mp3");
				Message m = new Message();
				m.what = 1;
				handler.sendMessage(m);
			}
		}).start();
	}

url的組成 ip+端口+web工程名(服務端)+servlet名。 apache

Servlet配置文件以下: app

<servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>Reciver</servlet-name>
    <servlet-class>com.younchen.servlet.Reciver</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>Reciver</servlet-name>
    <url-pattern>/Reciver</url-pattern>
  </servlet-mapping>


客戶端上傳文件代碼: ide

public static int uploadFile(String uploadUrl, String filename) {
		// Toast.makeText(this, "1111", Toast.LENGTH_LONG).show();
		String end = "\r\n";
		String twoHyphens = "--";
		String boundary = "******";
		try {
			URL url = new URL(uploadUrl);
			HttpURLConnection httpURLConnection = (HttpURLConnection) url
					.openConnection();
			// 設置每次傳輸的流大小,能夠有效防止手機由於內存不足崩潰
			// 此方法用於在預先不知道內容長度時啓用沒有進行內部緩衝的 HTTP 請求正文的流。
			httpURLConnection.setChunkedStreamingMode(1024 * 1024);// 1024K
			// 容許輸入輸出流
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setUseCaches(false);
			// 使用POST方法
			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=\"uploadedfile\";filename=\""
					+ filename + "\"" + end);

			dos.writeBytes(end);

			FileInputStream fis = new FileInputStream(FileCache.FilePath
					+ File.separator + filename);
			byte[] buffer = new byte[8192]; // 8k
			int count = 0;
			// 讀取文件
			System.out.println("可讀大小:" + fis.available());
			while ((count = fis.read(buffer)) != -1) {
				System.out.println("count");
				dos.write(buffer, 0, count);
			}
			fis.close();

			dos.writeBytes(end);
			dos.writeBytes(twoHyphens + boundary + twoHyphens + end);
			dos.flush();

			dos.close();

			InputStream is = httpURLConnection.getInputStream();
			InputStreamReader isr = new InputStreamReader(is, "utf-8");
			BufferedReader br = new BufferedReader(isr);
			String result = br.readLine();

			System.out.println(result);

			dos.close();
			is.close();
			return 1;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return -1;

	}

另外別忘記加權限: sd卡寫的權限和 internate權限 post

相關文章
相關標籤/搜索