我想僅使用url連接將視頻連同該視頻的縮略圖一起上傳到服務器。我可以上傳視頻,但我不知道如何同時上傳圖片。如何使用HttpUrl連接在服務器上上傳圖片和視頻?
這裏是我的代碼,以供參考:
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String existingFileName = selectedPath;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
String responseFromServer = "";
String urlString = "http://xxx/yyy/zzz/hh.php; //path of the php file on server
try
{
//------------------ CLIENT REQUEST
FileInputStream fileInputStream = new FileInputStream(new File(existingFileName));
// open a URL connection to the Servlet
URL url = new URL(urlString);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// Allow Inputs
conn.setDoInput(true);
// Allow Outputs
conn.setDoOutput(true);
// Don't use a cached copy.
conn.setUseCaches(false);
// Use a post method.
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
bmThumbnail = ThumbnailUtils.createVideoThumbnail(existingFileName,
Thumbnails.MICRO_KIND);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data;name=\"uploadedfile\";filename=\"" + existingFileName +"\"" + lineEnd);
// dos.writeBytes(bmThumbnail);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
//check server response
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.i("file sent to:" +existingFileName,"Code:" + serverResponseCode +"Message: "+ serverResponseMessage);
// close streams
Log.e("Debug","File is written");
fileInputStream.close();
dos.flush();
dos.close();
有什麼建議?提前致謝。
看http://stackoverflow.com/questions/7037717/upload-an-image-and-audio-in-one-request-in-android/7038888#7038888 – user370305 2012-07-10 12:25:51
感謝您的建議,但我們可以用它在我們的網址連接代碼? – user1514733 2012-07-10 12:31:54