我写这段代码发送一个文件到服务器:
路径=到文件要发送的绝对路径。其余的参数似乎不言自明。
public static String sendFileToServer(String path, String urlString,
String mimeType, String id) throws Exception {
try {
String URL = "", file_name = "";
if (!path.equals("")) {
file_name = path.substring(path.lastIndexOf("/") + 1);
}
File directory = new File(path);
byte[] data = new byte[(int) directory.length()];
try {
FileInputStream fileInputStream = new FileInputStream(directory);
fileInputStream.read(data);
} catch (FileNotFoundException e) {
System.out.println("File Not Found.");
e.printStackTrace();
} catch (IOException e1) {
System.out.println("Error Reading The File.");
e1.printStackTrace();
}
URL = Constants.WEB_ROOT_URL + urlString;
Log.v("AppEngine Manager", "Image Upload URL: " + URL);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(URL);
ByteArrayBody bab = new ByteArrayBody(data, file_name);
MultipartEntity reqEntity = new MultipartEntity(
HttpMultipartMode.BROWSER_COMPATIBLE);
reqEntity.addPart("media_type", new StringBody(mimeType));
reqEntity.addPart("file_name", new StringBody(file_name));
reqEntity.addPart("file_id", new StringBody(file_name));
reqEntity.addPart("file", bab);
postRequest.setEntity(reqEntity);
HttpResponse response = httpClient.execute(postRequest);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
return s + "";
} catch (Exception e) {
// handle exception here
Log.e(e.getClass().getName(), e.getMessage());
return "exception";
}
}