0
我想上傳文件到服務器,爲此我嘗試了很多不同的代碼,但我無法取得成功。黑莓文件上傳到服務器
在這段代碼連接成功創建,但在閱讀文件,並通過創建標題發佈數據到服務器的時間......
class ConnectionThread extends Thread
{
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String boundary = "*****";
String lineEnd = "\r\n";
String twoHyphens = "--";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 2*1024*1024;
DataInputStream fileInputStream = null;
public void run()
{
try {
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection("http://www.myserver/upload.php");
if (connDesc != null)
{
HttpConnection conn;
conn = (HttpConnection)connDesc.getConnection();
conn.setRequestMethod(conn.POST);
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream(conn.openDataOutputStream());
outputStream.writeChars(twoHyphens + boundary + lineEnd);
outputStream.writeChars("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + "files:///SDCard/bb.txt" +"\"" + lineEnd);
outputStream.writeChars(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
FileConnection fis=(FileConnection)Connector.open("file:///SDCard/bb.txt");
InputStream inputStream = fis.openInputStream();
ByteArrayOutputStream bos=new ByteArrayOutputStream();
int buffersize=1024*1024;
byte[] buffer=new byte[buffersize];
int length=0;
while((length=inputStream.read(buffer))!=-1)
{
bos.write(buffer,0,length);
}
byte[] imagedata=bos.toByteArray();
outputStream.write(imagedata);
outputStream.writeChars(lineEnd);
outputStream.writeChars(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = conn.getResponseCode();
final String serverResponseMessage = conn.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
}
catch (Exception e) {
}
}
PLZ有人幫助...在此先感謝..
在那裏有什麼問題嗎? – donturner 2012-08-17 13:39:12
當您嘗試調試無法正常工作的代碼時,有一個異常捕獲處理程序什麼也不做,並安靜地捕獲異常總是一個壞主意。至少,做'catch(Exception e){e.printStackTrace()}'。看看你是否得到一個例外。那麼,如果你是這樣,請將其與你的問題一起發佈。 – Nate 2012-08-18 02:47:28