从上传的Android图像MySQL数据库 [英] Uploading an image from Android to MySQL database
本文介绍了从上传的Android图像MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
美好的一天!我试图寻找从上传Android的图像文件到网上MySQL数据库的基础教程,但我找不到任何。
Good day! I am trying to search for a basic tutorial of uploading an image file from Android to an online MySQL database, but I can't find any.
我现在正在做,可以从Android上传用户的个人资料图片联机服务器的活动。
I am now making an activity that can upload a user's profile picture from the Android to the online server.
我需要的是像显示一个按钮,当它被点击,用户可以选择从文件的映像。可有人指导我这样做呢?提前致谢!
What I need is like displaying a button and when it's clicked, a user can choose an image from the files. Can someone guide me on doing this? Thanks in advance!
推荐答案
在客户端,你可以做到这一点。
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "path of the image.jpeg";
String urlServer = "http://xxx.xxx.xxx.xxx/uploader.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;
try {
FileInputStream fileInStream = new FileInputStream(new File(pathToOurFile) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
serverResponseCode = connection.getResponseCode();
serverResponseMessage = connection.getResponseMessage();
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
服务器端
<?php
$target_path = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "Success";
} else{
echo "Error";
}
?>
这篇关于从上传的Android图像MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文