我做了什么?
目前我正在使用drawable中的图像将图像发布到服务器
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.image);
我想做什么?
C:\images\
中选择所有样本图像
位于注意 ::图片位置,我不是指SD卡....我指的是我的电脑中的文件夹
MainActivity.java
public class MainActivity extends Activity {
Button submit;
ProgressDialog pDialog;
InputStream is;
EditText name;
ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
submit = (Button) findViewById(R.id.SUBMIT_BUTTON_ID);
name = (EditText) findViewById(R.id.editText1);
imageView = (ImageView) findViewById(R.id.imageView1);
submit.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new MainTest().execute();
}
});
}
/**
* Method to post the image to the server.
* U will have to change the url which will accept the image data.
* @throws IOException
*/
public void postImageData() {
try
{
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.image);
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://10.0.2.2:7002/Details/");
MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
try{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmapOrg.compress(CompressFormat.JPEG, 75, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "image.jpg");
reqEntity.addPart("key", bab);
reqEntity.addPart("key1", new StringBody(name.getText().toString()));
}
catch(Exception e){
//Log.v("Exception in Image", ""+e);
reqEntity.addPart("picture", new StringBody(""));
}
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);
}
}catch(Exception e){
e.getStackTrace();
}
}
public class MainTest extends AsyncTask<String, Integer, String> {
@Override
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading..");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
postImageData();
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// data=jobj.toString();
pDialog.dismiss();
}
}
}
activity_main.xml中
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="168dp"
android:layout_weight="0.41"
android:orientation="vertical"
tools:context=".MainActivity" >
<ImageView
android:id="@+id/imageView1"
android:layout_width="match_parent"
android:layout_height="101dp"
android:layout_marginTop="32dp"
android:clickable="false"
android:src="@drawable/image" />
<EditText
android:id="@+id/editText1"
android:layout_width="195dp"
android:layout_height="wrap_content"
android:paddingTop="50dp"
android:layout_gravity="center"
android:ems="10" />
</LinearLayout>
<Button
android:id="@+id/SUBMIT_BUTTON_ID"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="47dp"
android:text="SUBMIT" />
</LinearLayout>
关于实现这一目标的任何想法
感谢
答案 0 :(得分:1)
您有两个选择
1&gt;在您的PC中构建您自己的服务器,以便加载所有可用的图像和图像URI,并为其创建REST api,从而通过JSON将所有图像从PC恢复到任何地方。这样,您可以在手机中加载图片,可以共享,上传任何图片。例如,您可以使用this方法上传所选图片。
2&gt;简单方法:
在项目中使用aFilechooser librery,以便您可以直接从3rd party apps(例如:ES文件资源管理器)中选择图像/文件,这样您就可以从电脑中选择文件并允许将任何文件图像从您的电脑上传到您的服务器。这种方法唯一的问题是你必须查看图像,来自其他第三方应用程序的文件!如果需要,您可以使用Google云端硬盘同步机制同步您电脑上的所有图片文件夹或Use Google API。
答案 1 :(得分:0)
public int upLoad2Server(String pdid, String sourceFileUri, String imgtype) throws JSONException, IOException,MalformedURLException,FileNotFoundException {
/**
* create json object and pass into the webservice basic parameter
*/
jsonObjAuth=new JSONObject();
/*try {*/
//jsonObjAuth.put("image", sourceFileUri);
jsonObjAuth.put("user", UserInfo.username);
jsonObjAuth.put("pass", UserInfo.userpass);
jsonObjAuth.put("user_id", UserInfo.user_id);
jsonObjAuth.put("patientid", UserInfo.user_id);
jsonObjAuth.put("type", imgtype);
jsonObjAuth.put("pdid", pdid);
/*} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
//webservice uri
String upLoadServerUri =URLS.WS_BASE_URL+URLS.WS_ADD_IMAGE;
// String [] string = sourceFileUri;
String fileName = sourceFileUri;
HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";
File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return 0;
}
/*try {*/
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP
// connection to
// the URL
Log.i("URL_new","conn="+url+"="+conn);
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary);
// "Content-Disposition: form-data; name=\"image";
// filename=\"TypeA.png"\r\n"
// String
Log.i("data", "json " + jsonObjAuth.toString());
//conn.setRequestProperty("data", jsonObjAuth.toString());
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"image\";filename=\""
+ imgtype + "\"" + lineEnd);
Log.i("imgtype","filename:"+imgtype);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available(); // create a buffer of
// maximum size
Log.i("Huzza", "Initial .available : " + bytesAvailable);
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);
///////dharmesh
dos.writeBytes(twoHyphens + boundary + lineEnd);
String json= jsonObjAuth.toString();
dos.writeBytes("Content-Disposition: form-data; name=\"data\"\r\n\r\n" + json + "\r\n");
//[myReturn appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n%@\r\n",[formKeys objectAtIndex:i],[myDictionary valueForKey:[formKeys objectAtIndex:i]]] dataUsingEncoding:NSASCIIStringEncoding]];
///////
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
//serverResponseCode = conn.getResponseCode();
//String serverResponseMessage = conn.getResponseMessage();
// close streams
Log.i("Upload file to server", fileName + " File is written");
/*Log.i("Upload file to server", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);*/
fileInputStream.close();
dos.flush();
dos.close();
/*} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */
// this block will give the response of upload link
/*try {*/
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
while ((line = rd.readLine()) != null) {
Log.i("Huzza", "RES Message: " + line);
}
rd.close();
/*} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}*/
return serverResponseCode; // like 200 (Ok)
} // end upLoad2Server
我希望它对你有用....如果有任何疑问,请告诉我我的代码。