首頁 / CompScience / Programming / Languages / java / j2me / 使用J2ME的HTTP Post方式之多段文件上傳

使用J2ME的HTTP Post方式之多段文件上傳

這一篇是我在HTTP Post multipart file upload with J2ME的中文翻譯,網址在使用J2ME的HTTP Post方式之多段文件上傳
為了備份,並轉貼在此:

這裡有個J2ME類別用來透過HTTP POST多段請求方式處理檔案上傳。

程式碼:HttpMultipartRequest類別

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

public class HttpMultipartRequest
{
	static final String BOUNDARY = "----------V2ymHFg03ehbqgZCaKO6jy";

	byte[] postBytes = null;
	String url = null;

	public HttpMultipartRequest(String url, Hashtable params, String fileField, String fileName, String fileType, byte[] fileBytes) throws Exception
	{
		this.url = url;

		String boundary = getBoundaryString();

		String boundaryMessage = getBoundaryMessage(boundary, params, fileField, fileName, fileType);

		String endBoundary = "\r\n--" + boundary + "--\r\n";

		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		bos.write(boundaryMessage.getBytes());

		bos.write(fileBytes);

		bos.write(endBoundary.getBytes());

		this.postBytes = bos.toByteArray();

		bos.close();
	}

	String getBoundaryString()
	{
		return BOUNDARY;
	}

	String getBoundaryMessage(String boundary, Hashtable params, String fileField, String fileName, String fileType)
	{
		StringBuffer res = new StringBuffer("--").append(boundary).append("\r\n");

		Enumeration keys = params.keys();

		while(keys.hasMoreElements())
		{
			String key = (String)keys.nextElement();
			String value = (String)params.get(key);

			res.append("Content-Disposition: form-data; name=\"").append(key).append("\"\r\n")    
				.append("\r\n").append(value).append("\r\n")
				.append("--").append(boundary).append("\r\n");
		}
		res.append("Content-Disposition: form-data; name=\"").append(fileField).append("\"; filename=\"").append(fileName).append("\"\r\n") 
			.append("Content-Type: ").append(fileType).append("\r\n\r\n");

		return res.toString();
	}

	public byte[] send() throws Exception
	{
		HttpConnection hc = null;

		InputStream is = null;

		ByteArrayOutputStream bos = new ByteArrayOutputStream();

		byte[] res = null;

		try
		{
			hc = (HttpConnection) Connector.open(url);

			hc.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + getBoundaryString());

			hc.setRequestMethod(HttpConnection.POST);

			OutputStream dout = hc.openOutputStream();

			dout.write(postBytes);

			dout.close();

			int ch;

			is = hc.openInputStream();

			while ((ch = is.read()) != -1)
			{
				bos.write(ch);
			}
			res = bos.toByteArray();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(bos != null)
					bos.close();

				if(is != null)
					is.close();

				if(hc != null)
					hc.close();
			}
			catch(Exception e2)
			{
				e2.printStackTrace();
			}
		}
		return res;
	}
}

範例使用

這裡有個程式碼片段用來透過HttpMultipartRequest類別來上傳一個檔案:

byte[] fileBytes = getFileBytes(); //retrieve file bytes with your own code

Hashtable params = new Hashtable();
params.put("custom_param", "param_value");
params.put("custom_param2", "param_value2");

HttpMultipartRequest req = new HttpMultipartRequest(
	"http://www.server.com/uploadScript.php",
	params,
	"upload_field", "original_filename.png", "image/png", fileBytes
);

byte[] response = req.send();

伺服器範例程式碼(PHP)

這個PHP範例程式用來處理上傳,它不會真正儲存上傳檔案,只會顯示一些關於上傳檔案的大小及參數的訊息。

<?php

$filesize = filesize($_FILES['upload_field']['tmp_name']);

echo "The uploaded file size is " . $filesize . " bytes\n";

foreach($_POST as $key => $value)
{
	echo "Parameter name: " . $key . ", value: " . $value . "\n";
}

?>
Print Friendly, PDF & Email
馬上成為工作達人的Fans

About ㄚ琪

工作達人Fun Taiwan的創辦者及總編,可以在這裡更認識他。

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

這個網站採用 Akismet 服務減少垃圾留言。進一步瞭解 Akismet 如何處理網站訪客的留言資料

Scroll To Top