gpt4 book ai didi

android - 图片无法在android中的服务器上上传

转载 作者:行者123 更新时间:2023-11-30 01:55:55 27 4
gpt4 key购买 nike

我正在从图库中获取图像并通过 php 将其放入服务器,一切都已完成但图像无法保存在服务器上请帮助我

   public int uploadFile (String sourceFileUri) {


String fileName = sourceFileUri;
String upLoadServerUri="http://thinksl.com/taughtable/update.php";
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(sourceFileUri);
int serverResponseCode = 0;
StrictMode.ThreadPolicy th= new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(th);

if (!sourceFile.isFile()) {



Log.e("uploadFile", "Source File not exist :"
);

runOnUiThread(new Runnable() {
public void run() {

}
});

return 0;

}
else
{
try {

// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
//String uploaded_file="image";
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
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);
conn.setRequestProperty("uploaded_file", fileName);

dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
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);

// Responses from the server (code and message)
serverResponseCode = conn.getResponseCode();
String serverResponseMessage = conn.getResponseMessage();

Log.e("uploadFile", "HTTP Response is : "
+ serverResponseMessage + ": " + serverResponseCode);

if(serverResponseCode == 200){

runOnUiThread(new Runnable() {
public void run() {

String msg = "File Upload Completed.\n\n See uploaded file here"
;

Toast.makeText(Edit_Profile.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}

//close the streams //
fileInputStream.close();
dos.flush();
dos.close();

} catch (MalformedURLException ex) {


ex.printStackTrace();

runOnUiThread(new Runnable() {
public void run() {

Toast.makeText(Edit_Profile.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});

Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {

e.printStackTrace();

runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(Edit_Profile.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
return serverResponseCode;

}

}

PHP文件

   $target = "uploads/"; 
$target1 =$target . date(U).( $_FILES['image']['name']);
$path="http://thinksl.com/taughtable/uploads/";
$image=$path . date(U).( $_FILES['image']['name']);
move_uploaded_file($_FILES['image']['tmp_name'], $target1);

最佳答案

这是我用来上传图片到服务器的方法。

/**
* Upload Image to server
*
* @param file image to be saved
* @param compressorQuality quality of image
* @return path of uploaded image in server
*/
private String uploadImage(Bitmap file, int compressorQuality) {
String final_upload_filename = "demo_image.png";
String response = null;
HttpURLConnection conn = null;
try {
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "---------------------------14737809831466499882746641449";
URL url = new URL("image_upload_url");
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", final_upload_filename);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"userfile\"; filename=\"" + final_upload_filename + "\"" + lineEnd);
dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
dos.writeBytes(lineEnd);
file.compress(CompressFormat.PNG, compressorQuality, dos);
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.flush();
dos.close();
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
byte[] bytes = new byte[1024];
while ((bytesRead = is.read(bytes)) != -1) {
baos.write(bytes, 0, bytesRead);
}
byte[] bytesReceived = baos.toByteArray();
baos.close();
is.close();
response = new String(bytesReceived);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (conn != null) {
conn.disconnect();
}
}
return response;
}

您可以像这样使用此方法:

Bitmap bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), imageUri);
String server_response = uploadImage(bitmap, 100);

希望对您有所帮助!

关于android - 图片无法在android中的服务器上上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32247981/

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