Android r) ); } 公共列表getListenerList(){ 返回listenerList; } }
然后使用HTTPOST代码将其上载到服务器Android r) ); } 公共列表getListenerList(){ 返回listenerList; } },android,Android,然后使用HTTPOST代码将其上载到服务器 import java.io.File; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.Multipart
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.os.AsyncTask;
import android.util.Log;
public class UploadToServer extends AsyncTask<String, String, String>{
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... aurl){
String status="";
final String URL= "";
Log.d("Image Path ======",DialogFile.fileName);
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
File file = new File(DialogFile.fileName);
FileBody bin = new FileBody(file);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("userImage", bin);
httppost.setEntity(reqEntity);
Log.d("executing request ", httppost.getRequestLine().toString());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
if (resEntity != null)
{
Log.d("Response content length: ",resEntity.getContentLength()+"");
if(resEntity.getContentLength()>0)
{
status= EntityUtils.toString(resEntity);
}
else
{
status= "No Response from Server";
Log.d("Status----->",status);
}
}
else
{
status= "No Response from Server";
Log.d("Status----->",status);
}
} catch (Exception e) {
e.printStackTrace();
status="Unable to connect with iPerform server";
}
return status;
}
}
导入java.io.File;
导入org.apache.http.HttpEntity;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.entity.mime.MultipartEntity;
导入org.apache.http.entity.mime.content.FileBody;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入android.os.AsyncTask;
导入android.util.Log;
公共类UploadToServer扩展异步任务{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
}
@凌驾
受保护的字符串背景(字符串…aurl){
字符串状态=”;
最终字符串URL=“”;
Log.d(“图像路径===”,DialogFile.fileName);
试一试{
HttpClient HttpClient=新的DefaultHttpClient();
HttpPost HttpPost=新的HttpPost(URL);
File File=新文件(DialogFile.fileName);
FileBody bin=新的FileBody(文件);
MultipartEntity reqEntity=新的MultipartEntity();
reqEntity.addPart(“用户图像”,bin);
httppost.setEntity(reqEntity);
Log.d(“正在执行请求”,httppost.getRequestLine().toString());
HttpResponse response=httpclient.execute(httppost);
HttpEntity当前性=response.getEntity();
if(最近性!=null)
{
Log.d(“响应内容长度:”,resEntity.getContentLength()+);
if(resEntity.getContentLength()>0)
{
status=EntityUtils.toString(最近性);
}
其他的
{
status=“服务器无响应”;
Log.d(“状态------>”,状态);
}
}
其他的
{
status=“服务器无响应”;
Log.d(“状态------>”,状态);
}
}捕获(例外e){
e、 printStackTrace();
status=“无法连接iPerform服务器”;
}
返回状态;
}
}
您可以检查这个答案
或者使用自定义文件对话框,例如
试试这个:
Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
intent.setType("image/*");
intent.putExtra("return-data", true);
startActivityForResult(intent, 1);
然后,此代码用于设置从库中选择的图像。使用onActivityResult方法从库中获取结果:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
Uri _uri = data.getData();
String yourimagepath = getRealPathFromURI(_uri);
...
// your code goes here
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
希望它能有所帮助。此代码将帮助您:
String boundary = "---------------------------14737809831466499882746641449";
String lineEnd = "\r\n", p;
String twoHyphens = "--";
HttpURLConnection conn;
DataOutputStream dos = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
DataInputStream inStream;
File sourceFile;
ArrayList<String> tempList = new ArrayList<String>();
String exsistingFileName = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/PiyushAushFish";
try {
File f = new File(exsistingFileName);
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
tempList.add(file.getPath());
Log.v("Existing", exsistingFileName);
}
// tempList.add(exsistingFileName);
// tempList.add(FileName);
if (isUploaded) {
URL url = new URL(
"You URL here");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"text/plain; charset=utf-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
for (int i = 0; i < tempList.size(); i++) {
Log.v("Length", tempList.size() + "");
sourceFile = new File(tempList.get(i));
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
Log.v("IMAGPATH", sourceFile + "");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
System.out
.println("==========================image name================="
+ sourceFile);
dos.writeBytes("Content-Disposition: form-data; name=\"image[]\"; filename=\""
+ sourceFile + "\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream"
+ lineEnd + lineEnd);
System.out
.println("=============================data writin start================");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
System.out
.println("==============================bytesRead==========================="
+ bytesRead);
}
dos.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
}
dos.flush();
dos.close();
} else {
Log.v("Error.....", "No Data");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Error--------->", e.getMessage());
e.printStackTrace();
}
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.e("server response codde", "" + serverResponseCode);
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage
+ ": " + serverResponseCode);
if (serverResponseCode == 200) {
isUploaded = true;
// isUploaded = (c.getInt(23) == 1);
Log.v("Upload", "Successfully");
}
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}
String boundary=“------------------------------------14737809831466499882746641449”;
字符串lineEnd=“\r\n”,p;
字符串双连字符=“--”;
httpurl连接连接;
DataOutputStream dos=null;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1*1024*1024;
流内数据输入流;
文件源文件;
ArrayList tempList=新的ArrayList();
String exsistingFileName=Environment.getExternalStorageDirectory()
.getAbsolutePath()+“/PiyushAushFish”;
试一试{
文件f=新文件(现有文件名);
File[]files=f.listFiles();
对于(int i=0;i0){
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
系统输出
.println(“===========================================================================================================================================================================================”
+字节读取);
}
dos.writeBytes(lineEnd+twoHyphens+boundary+twoHyphens
+线路端);
fileInputStream.close();
}
dos.flush();
dos.close();
}否则{
Log.v(“错误…”,“否
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
Uri _uri = data.getData();
String yourimagepath = getRealPathFromURI(_uri);
...
// your code goes here
}
super.onActivityResult(requestCode, resultCode, data);
}
public String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
String boundary = "---------------------------14737809831466499882746641449";
String lineEnd = "\r\n", p;
String twoHyphens = "--";
HttpURLConnection conn;
DataOutputStream dos = null;
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
DataInputStream inStream;
File sourceFile;
ArrayList<String> tempList = new ArrayList<String>();
String exsistingFileName = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/PiyushAushFish";
try {
File f = new File(exsistingFileName);
File[] files = f.listFiles();
for (int i = 0; i < files.length; i++) {
File file = files[i];
tempList.add(file.getPath());
Log.v("Existing", exsistingFileName);
}
// tempList.add(exsistingFileName);
// tempList.add(FileName);
if (isUploaded) {
URL url = new URL(
"You URL here");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"text/plain; charset=utf-8");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("Content-Type",
"multipart/form-data; boundary=" + boundary);
for (int i = 0; i < tempList.size(); i++) {
Log.v("Length", tempList.size() + "");
sourceFile = new File(tempList.get(i));
FileInputStream fileInputStream = new FileInputStream(
sourceFile);
Log.v("IMAGPATH", sourceFile + "");
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
System.out
.println("==========================image name================="
+ sourceFile);
dos.writeBytes("Content-Disposition: form-data; name=\"image[]\"; filename=\""
+ sourceFile + "\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream"
+ lineEnd + lineEnd);
System.out
.println("=============================data writin start================");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
System.out
.println("==============================bytesRead==========================="
+ bytesRead);
}
dos.writeBytes(lineEnd + twoHyphens + boundary + twoHyphens
+ lineEnd);
fileInputStream.close();
}
dos.flush();
dos.close();
} else {
Log.v("Error.....", "No Data");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Error--------->", e.getMessage());
e.printStackTrace();
}
try {
inStream = new DataInputStream(conn.getInputStream());
String str;
while ((str = inStream.readLine()) != null) {
Log.e("Debug", "Server Response " + str);
}
inStream.close();
int serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();
Log.e("server response codde", "" + serverResponseCode);
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage
+ ": " + serverResponseCode);
if (serverResponseCode == 200) {
isUploaded = true;
// isUploaded = (c.getInt(23) == 1);
Log.v("Upload", "Successfully");
}
} catch (IOException ioex) {
Log.e("Debug", "error: " + ioex.getMessage(), ioex);
}