使用PHP将文件从android(java)上传到服务器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20995118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uploading file from android (java) to server using PHP
提问by dasdasd
Hello Im trying to upload files from my android application to my server using PHP.
您好,我正在尝试使用 PHP 将文件从我的 android 应用程序上传到我的服务器。
I have read this posts:
我已经阅读了这篇文章:
How to upload a file using Java HttpClient library working with PHPhttp://www.veereshr.com/Java/UploadHow do I send a file in Android from a mobile device to server using http?
如何使用使用 PHP 的 Java HttpClient 库上传文件http://www.veereshr.com/Java/Upload如何在 Android 中使用 http 将文件从移动设备发送到服务器?
This is my JAVA code:
这是我的JAVA代码:
public void upload() throws Exception {
File file = new File("data/data/com.tigo/databases/exercise");
Log.i("file.getName()", file.getName());
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");
InputStreamEntity reqEntity = new InputStreamEntity( new FileInputStream(file), -1);
reqEntity.setContentType("binary/octet-stream");
reqEntity.setChunked(true);
httppost.setEntity(reqEntity);
HttpResponse response = httpclient.execute(httppost);
if((response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")){
// Successfully Uploaded
Log.i("uploaded", response.getStatusLine().toString());
}
else{
// Did not upload. Add your logic here. Maybe you want to retry.
Log.i(" not uploaded", response.getStatusLine().toString());
}
httpclient.getConnectionManager().shutdown();
}
This is my PHP code:
这是我的 PHP 代码:
<?php
$uploads_dir = '/tigo/databaseBackup';
if (is_uploaded_file($_FILES['exercise']['tmp_name']))
{
$info = "File ". $_FILES['exercise']['name'] ." uploaded successfully.\n";
$file = 'emailTest.log';
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
move_uploaded_file ($_FILES['exercise'] ['tmp_name'], $_FILES['exercise'] ['name']);
}
else
{
$info = "Possible file upload attack: ";
$file = 'emailTest.log';
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
$info = "filename '". $_FILES['exercise']['tmp_name'] . "'.";
file_put_contents($file, $info, FILE_APPEND | LOCK_EX);
print_r($_FILES);
}
?>
In my logcat i get HTTP/1.1 200 OK. When i look at the server logs i get this error:
在我的 logcat 中,我得到 HTTP/1.1 200 OK。当我查看服务器日志时,出现此错误:
PHP Notice: Undefined index: exercise in /var/www/backDatabase.php on line 23
I also tried to use:
我也尝试使用:
$_FILES['userfile']['name']
Instead of
代替
$_FILES['exercise']['tmp_name']
And i got the same error in my server logs.
我在我的服务器日志中遇到了同样的错误。
I think my problem is that I cant get reference to my uploaded file.
我认为我的问题是我无法引用我上传的文件。
Thanks for helping.
谢谢你的帮助。
回答by CONvid19
Try this:
尝试这个:
JAVA code:
爪哇代码:
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
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.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
public class UploadFile {
public static void main(String[] args) throws Exception {
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("http://***.***.***.***/backDatabase.php");
File file = new File("/data/data/com.tigo/databases/exercise");
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file);
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println(response.getStatusLine());
if (resEntity != null) {
System.out.println(EntityUtils.toString(resEntity));
}
if (resEntity != null) {
resEntity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
}
}
PHP code:
PHP代码:
<?php
if (is_uploaded_file($_FILES['userfile']['tmp_name'])) {
echo "File ". $_FILES['userfile']['name'] ." uploaded successfully.\n";
move_uploaded_file ($_FILES['userfile'] ['tmp_name'], $_FILES['userfile'] ['name']);
} else {
echo "Possible file upload attack: ";
echo "filename '". $_FILES['userfile']['tmp_name'] . "'.";
print_r($_FILES); }
?>
You may need to change the paths in order to fit your needs, but the above code works.
您可能需要更改路径以满足您的需要,但上述代码有效。
回答by sachin10
try multipart entity
尝试多部分实体
public void upload(String filepath) throws IOException
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost httppost = new HttpPost("url");
File file = new File(filepath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");
mpEntity.addPart("userfile", cbFile);
httppost.setEntity(mpEntity);
System.out.println("executing request " + httppost.getRequestLine());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
// check the response and do what is required
}
回答by SAQLAIN RAZA
Upload Image on Web Server using Android / C# {Xamarin}
使用 Android / C# {Xamarin} 在 Web 服务器上上传图像
This is Just Small Piece of Code. it can send any image from Android to your Web Server using Android
这只是一小段代码。它可以使用 Android 将任何图像从 Android 发送到您的 Web 服务器
System.Net.WebClient Client = new System.Net.WebClient();
Client.Headers.Add("Content-Type", "binary/octet-stream");
byte[] result = Client.UploadFile("localhost/FolderName/upload.php", "POST", path);
string s = System.Text.Encoding.UTF8.GetString(result, 0, result.Length);
Here is the PHP Code {upload.php}. Create a Folder name { Uploads } in your Application.
这是 PHP 代码 {upload.php}。在您的应用程序中创建一个文件夹名称 { Uploads }。
<?php
$uploads_dir = 'uploads/'; //Directory to save the file that comes from client application.
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK)
{
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>