gpt4 book ai didi

android - 如何使用单击上传按钮上传特定列表图像

转载 作者:搜寻专家 更新时间:2023-11-01 08:58:04 27 4
gpt4 key购买 nike

每当用户单击 ListView 项目行中的上传按钮时,如何将特定图像上传到服务器

每当用户点击“上传”按钮时,使用下行在对话框中显示特定的图像名称:

 fileName=ImageList.get(position).toString().substring(strPath.lastIndexOf('/')+1, strPath.length());

OldUploadActivity.java:

            //  btnUpload
btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
btnUpload.setTextColor(Color.BLACK);
btnUpload.setTag(strPath);
btnUpload.setOnClickListener(new View.OnClickListener() {


@SuppressWarnings("deprecation")
public void onClick(View v) {
// Upload

fileName=ImageList.get(position).toString().substring(strPath.lastIndexOf('/')+1, strPath.length());

}
});



//Upload
public void startUpload(final int position) {
Runnable runnable = new Runnable() {

public void run() {
handler.post(new Runnable() {
public void run() {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);

// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
status.setText("Uploading..");

new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}


// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {

String resServer;
int position;

protected void onPreExecute() {

super.onPreExecute();
}

@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub

int position;

position = Integer.parseInt(params[0]);
Log.d("position::", " " + position);

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int resCode = 0;
String resMessage = "";

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String strSDPath;

// File Path
strSDPath = ImageList.get(position).toString();

// Upload to PHP Script
String strUrlServer = "http://10.0.2.2/res/files.php";

try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
return null;
}

FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));

URL url = new URL(strUrlServer);
HttpURLConnection conn = (HttpURLConnection) url.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 outputStream = new DataOutputStream(conn
.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
+ strSDPath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Response Code and Message
resCode = conn.getResponseCode();
if(resCode == HttpURLConnection.HTTP_OK)
{
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();

int read = 0;
while ((read = is.read()) != -1) {
bos.write(read);
}
byte[] result = bos.toByteArray();
bos.close();

resMessage = new String(result);
}

Log.d("resCode=",Integer.toString(resCode));
Log.d("resMessage=",resMessage.toString());

fileInputStream.close();
outputStream.flush();
outputStream.close();

resServer = resMessage.toString();

} catch (Exception ex) {
// Exception handling
return null;
}
return null;
}

protected void onPostExecute(Void unused) {
statusWhenFinish(position,resServer);
}
}

// when upload finish
protected void statusWhenFinish(int position, String resServer) {

View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());

// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);

// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
/*** Default Value ***/
String strStatusID = "0";
String strMessage = "Unknow Status!";

try {
JSONObject c = new JSONObject(resServer);
strStatusID = c.getString("StatusID");
strMessage = c.getString("Message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

// Prepare Status
if(strStatusID.equals("0"))
{
// When update Failed
status.setText( strMessage );
status.setTextColor(Color.RED);

// Enabled Button again
Button btnUpload = (Button) v.findViewById(R.id.btnUpload);
btnUpload.setText("Already Uploaded");
btnUpload.setTextColor(Color.RED);
btnUpload.setEnabled(true);
}
else
{
status.setText("Upload Completed");
status.setTextColor(Color.GREEN);
}
}

activity_column.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<ImageView
android:id="@+id/ColImgPath"
android:layout_width="110dp"
android:layout_height="110dp"
/>

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>

<TableLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/ColImgName"
android:text="Column 1" />


</TableRow>

<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content">

<TextView
android:id="@+id/ColStatus"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Status" />

</TableRow>

<TableRow
android:layout_width="wrap_content"
android:layout_height="wrap_content" >

<Button
android:id="@+id/btnUpload"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Upload" />

<Button
android:id="@+id/btnPrint"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Print" />


</TableRow>

</TableLayout>

</LinearLayout>

最佳答案

试试这段代码:

        btnUpload = (Button) convertView.findViewById(R.id.btnUpload);
btnUpload.setTextColor(Color.BLACK);
btnUpload.setTag(strPath);
btnUpload.setOnClickListener(new View.OnClickListener() {


@SuppressWarnings("deprecation")
public void onClick(View v) {
// Upload

startUpload(position);
fileName=ImageList.get(position).toString()
.substring(strPath.lastIndexOf('/')+1, strPath.length());

}
});



//Upload
public void startUpload(final int position) {
Runnable runnable = new Runnable() {

public void run() {
handler.post(new Runnable() {
public void run() {
View v = lstView.getChildAt(position - lstView.getFirstVisiblePosition());
// Show ProgressBar
ProgressBar progress = (ProgressBar)v.findViewById(R.id.progressBar);
progress.setVisibility(View.VISIBLE);

// Status
TextView status = (TextView)v.findViewById(R.id.ColStatus);
status.setText("Uploading..");

new UploadFileAsync().execute(String.valueOf(position));
}
});
}
};
new Thread(runnable).start();
}


// Async Upload
public class UploadFileAsync extends AsyncTask<String, Void, Void> {

String resServer;
int position;

protected void onPreExecute() {

super.onPreExecute();
}

@Override
protected Void doInBackground(String... params) {
// TODO Auto-generated method stub

int position;

position = Integer.parseInt(params[0]);
Log.d("position::", " " + position);

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
int resCode = 0;
String resMessage = "";

String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
String strSDPath;

// File Path
strSDPath = ImageList.get(position).toString();

// Upload to PHP Script
String strUrlServer = "http://10.0.2.2/res/files.php";

try {
/** Check file on SD Card ***/
File file = new File(strSDPath);
if(!file.exists())
{
resServer = "{\"StatusID\":\"0\",\"Error\":\"Please check path on SD Card\"}";
return null;
}

FileInputStream fileInputStream = new FileInputStream(new File(strSDPath));

URL url = new URL(strUrlServer);
HttpURLConnection conn = (HttpURLConnection) url.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 outputStream = new DataOutputStream(conn
.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream
.writeBytes("Content-Disposition: form-data; name=\"filUpload\";filename=\""
+ strSDPath + "\"" + lineEnd);
outputStream.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];

// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}

outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

// Response Code and Message
resCode = conn.getResponseCode();
if(resCode == HttpURLConnection.HTTP_OK)
{
InputStream is = conn.getInputStream();
ByteArrayOutputStream bos = new ByteArrayOutputStream();

int read = 0;
while ((read = is.read()) != -1) {
bos.write(read);
}
byte[] result = bos.toByteArray();
bos.close();

resMessage = new String(result);
}

Log.d("resCode=",Integer.toString(resCode));
Log.d("resMessage=",resMessage.toString());

fileInputStream.close();
outputStream.flush();
outputStream.close();

resServer = resMessage.toString();

} catch (Exception ex) {
// Exception handling
return null;
}
return null;
}

protected void onPostExecute(Void unused) {
statusWhenFinish(position,resServer);
}
}

关于android - 如何使用单击上传按钮上传特定列表图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17445910/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com