检查此代码以将文件从 Android 上传到 Web 服务器
public class UploadFileToServer extends AsyncTask<Object, String, Object>
{
URL connectURL;
String params;
String responseString;
String fileName;
byte[] dataToServer;
FileInputStream fileInputStream;
private int serverResponseCode;
private String serverResponseMessage;
private static final String TAG = "Uploader";
public void setUrlAndFile(String urlString, File fileName)
{
Log.d(TAG,"StartUploader");
try
{
fileInputStream = new FileInputStream(fileName);
connectURL = new URL(urlString);
}
catch(Exception e)
{
e.getStackTrace();
publishProgress(e.toString());
}
this.fileName = fileName.getAbsolutePath()+".txt";
}
synchronized void doUpload()
{
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
Log.d(TAG,"lv1");
try
{
Log.d(TAG,"doUpload");
publishProgress("Uploading...");
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection","Keep-Alive");
conn.setRequestProperty("Content-Type","multipart/form-data;boundary=" + boundary);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
Log.d(TAG,"LvA");
Log.d(TAG,twoHyphens + boundary + lineEnd + ";Content-Disposition:form-data; name=\"Uploaded\";filename=\"" + fileName + "\"" + lineEnd);
int bytesAvailable = fileInputStream.available();
int maxBufferSize = 1024;
int bufferSize = Math.min(bytesAvailable, maxBufferSize);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer,0, bufferSize);
Log.d(TAG,"LvB");
while(bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
fileInputStream.close();
dos.flush();
InputStream is = conn.getInputStream();
int ch;
Log.d(TAG,"LvC");
StringBuffer buff = new StringBuffer();
while((ch=is.read()) != -1)
{
buff.append((char)ch);
}
// publishProgress(buff.toString());
dos.close();
// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
serverResponseMessage = conn.getResponseMessage();
// Log.d(TAG,"Buffer "+buff.toString());
Log.d(TAG,"Server Response "+serverResponseMessage);
}
catch(Exception e)
{
e.getStackTrace();
publishProgress(e.toString());
}
}
@Override
protected Object doInBackground(Object... arg0)
{
Log.d(TAG,"lv1a");
doUpload();
Log.d(TAG,"Uploading Completed! Path: "+connectURL);
return null;
}
protected void onProgressUpdate(String... progress)
{
//this.info.setText(progress[0]);
Log.d("Progress", progress[0]);
}
}
谢谢