安卓:上传到PHP服务器映像 [英] Android : Upload image to PHP server
问题描述
我有写上载从相机拍摄到我的服务器映像的脚本。我得到的 200 OK 的反应,但我不认为我的形象我在上传服务器/文件夹:
也许我的脚本包含一个错误。你能帮助我吗?
我的例子是以下链接:<一href="http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106" rel="nofollow">http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106
下面是compleete安卓类:
进口java.io.DataOutputStream中;
进口的java.io.File;
进口java.io.FileInputStream中;
进口java.io.FileNotFoundException;
进口java.net.HttpURLConnection中;
进口java.net.MalformedURLException;
进口的java.net.URL;
进口java.text.SimpleDateFormat的;
进口java.util.Date;
进口android.app.ActionBar;
进口android.app.Activity;
进口android.app.ProgressDialog;
进口android.content.Intent;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.graphics.Color;
进口android.graphics.drawable.ColorDrawable;
进口android.net.Uri;
进口android.os.Bundle;
进口android.os.Environment;
进口android.provider.MediaStore;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.ImageButton;
进口android.widget.ImageView;
进口android.widget.TextView;
进口android.widget.Toast;
公共类New_annonce_act_step3延伸活动{
私有静态最终诠释REQUEST_IMAGE = 100;
TextView的tvPath;
TextView的txtHaut;
ImageView的preVIEW;
文件的目标;
字符串的ImagePath;
的ImageButton takePhoto;
按钮的BtnCreate;
INT serverResponse code = 0;
ProgressDialog对话框= NULL;
字符串upLoadServerUri = NULL;
@覆盖
保护无效的onCreate(包savedInstanceState){
// TODO自动生成方法存根
super.onCreate(savedInstanceState);
的setContentView(R.layout.nouvelle_annonce_step3);
//更改操作栏颜色
动作条酒吧= getActionBar();
bar.setBackgroundDrawable(新ColorDrawable(Color.parseColor(#0099CC)));
preVIEW =(ImageView的)findViewById(R.id.nouvelle_annonce_step3_phototaken_ preVIEW);
的BtnCreate =(按钮)findViewById(R.id.nouvelle_annonce_step3_btn);
txtHaut =(TextView中)findViewById(R.id.nouvelle_annonce_step3_texteHaut);
takePhoto =(的ImageButton)findViewById(R.id.nouvelle_annonce_choose_image);
preview.setVisibility(View.GONE);
upLoadServerUri =http://mywebsite.com/database/PDO/uploadFile.php;
字符串名称= dateToString(新日期(),YYYY-MM-DD-HH-MM-SS);
目标=新的文件(Environment.getExternalStorageDirectory()名+.JPG);
takePhoto.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
意向意图=新的意图(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(目标));
startActivityForResult(意向,REQUEST_IMAGE);
}
});
btnCreate.setOnClickListener(新OnClickListener(){
@覆盖
公共无效的onClick(视图v){
对话框= ProgressDialog.show(New_annonce_act_step3.this,,上传文件...,真正的);
新主题(新的Runnable(){
公共无效的run(){
uploadFile(的ImagePath);
}
})。开始();
}
});
}
@覆盖
保护无效onActivityResult(INT申请code,INT结果code,意图数据){
如果(要求code == REQUEST_IMAGE和放大器;&安培;结果code == Activity.RESULT_OK){
尝试 {
preview.setVisibility(View.VISIBLE);
takePhoto.setVisibility(View.GONE);
txtHaut.setText(Cette形象共青parfaite!);
在的FileInputStream =新的FileInputStream(目标);
BitmapFactory.Options选项=新BitmapFactory.Options();
options.inSampleSize = 10;
的ImagePath = destination.getAbsolutePath();
Log.d(信息,PATH ===+的ImagePath);
//tvPath.setText(imagePath);
BMP位= BitmapFactory.de codeStream(在,空,期权);
preview.setImageBitmap(BMP);
}赶上(FileNotFoundException异常E){
e.printStackTrace();
}
}
其他{
tvPath.setText(申请注销);
}
}
公共字符串dateToString(日期日期,字符串格式){
SimpleDateFormat的DF =新的SimpleDateFormat(格式);
返回df.format(日期);
}
公众诠释uploadFile(字符串sourceFileUri){
字符串文件名= sourceFileUri;
HttpURLConnection的康恩= NULL;
DataOutputStream类DOS = NULL;
字符串lineEnd =\ r \ N的;
串twoHyphens = - ;
字符串边界=*****;
INT读取动作,方bytesAvailable,缓冲区大小;
byte []的缓冲区;
INT maxBufferSize = 1 * 1024 * 1024;
文件的SourceFile =新的文件(sourceFileUri);
如果(!sourceFile.isFile()){
dialog.dismiss();
Log.e(一个UploadFile,源文件不存在:+的ImagePath);
返回0;
}
其他
{
尝试 {
//打开一个URL连接到这个Servlet
的FileInputStream的FileInputStream =新的FileInputStream(的资源文件);
网址URL =新的URL(upLoadServerUri);
//打开一个HTTP连接网址
康恩=(HttpURLConnection类)url.openConnection();
conn.setDoInput(真正的); //允许输入
conn.setDoOutput(真正的); //允许输出
conn.setUseCaches(假); //不要使用缓存副本
conn.setRequestMethod(POST);
conn.setRequestProperty(连接,保持活动);
conn.setRequestProperty(ENCTYPE,多部分/表单数据);
conn.setRequestProperty(内容类型,多部分/格式数据;边界=+界);
conn.setRequestProperty(uploaded_file,文件名);
DOS =新DataOutputStream类(conn.getOutputStream());
dos.writeBytes(twoHyphens +边界+ lineEnd);
dos.writeBytes(内容处置:表格数据;名称= \uploaded_file \;文件名=+文件名++ lineEnd);
dos.writeBytes(lineEnd);
//创建最大大小的缓冲区
方bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
缓冲区=新的字节[BUFFERSIZE]
//读取文件,并将其写入形式...
读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
而(读取动作大于0){
dos.write(缓冲液,0,BUFFERSIZE);
方bytesAvailable = fileInputStream.available();
BUFFERSIZE = Math.min(方bytesAvailable,maxBufferSize);
读取动作= fileInputStream.read(缓冲液,0,BUFFERSIZE);
}
//发送多部分表格数据文件数据后necesssary ...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);
从服务器//回应(code和消息)
serverResponse code = conn.getResponse code();
串serverResponseMessage = conn.getResponseMessage();
Log.i(一个UploadFile,HTTP响应是:+ serverResponseMessage +:+ serverResponse code);
如果(serverResponse code == 200){
runOnUiThread(新的Runnable(){
公共无效的run(){
Toast.makeText(New_annonce_act_step3.this,文件上传完成。,
Toast.LENGTH_SHORT).show();
}
});
}
//关闭流//
fileInputStream.close();
dos.flush();
dos.close();
}赶上(MalformedURLException的前){
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(新的Runnable(){
公共无效的run(){
Toast.makeText(New_annonce_act_step3.this,MalformedURLException的,
Toast.LENGTH_SHORT).show();
}
});
Log.e(上传文件到服务器,错误:+ ex.getMessage(),前);
}赶上(例外五){
dialog.dismiss();
e.printStackTrace();
runOnUiThread(新的Runnable(){
公共无效的run(){
Toast.makeText(New_annonce_act_step3.this,得到了异常:看logcat的,
Toast.LENGTH_SHORT).show();
}
});
Log.e(上传文件到服务器异常,异常
+ e.getMessage(),E);
}
dialog.dismiss();
返回serverResponse code;
} //结束else块
}
}
这里是 PHP脚本:
&LT; PHP
$ FILE_PATH =上传/;
$ FILE_PATH = $ FILE_PATH。基本名($ _ FILES ['uploaded_file'] ['名称']);
如果(move_uploaded_file($ _ FILES ['uploaded_file'] ['tmp_name的值'],$ FILE_PATH)){
回声成功;
} 其他{
回声不及格;
}
?&GT;
你有没有验证的用户阿帕奇
(或任何用户的PHP运行时)有写入权限在 $ FILE_PATH
?
将下面的code在同一目录下的PHP脚本,然后访问它的Web浏览器。
&LT; PHP
$ FILE_PATH ='上传/';
$成功= file_put_contents($ FILE_PATHå文件,这是一个测试);
如果($成功=== FALSE){
回声无法写入文件;
} 其他 {
回声中写道$成功字节;
}
?&GT;
这是否给一个成功的信息或错误信息?
如果它给出了一个错误信息,试图改变上传
目录的所有权。
I have write a script to upload an image taken from camera to my server. I get 200OK response but I don't see my image on my server in uploads/ folder :
Maybe my script contain an error. Could you help me please ?
My example is the following link : http://androidexample.com/Upload_File_To_Server_-_Android_Example/index.php?view=article_discription&aid=83&aaid=106
Here is the compleete Android class :
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
public class New_annonce_act_step3 extends Activity {
private static final int REQUEST_IMAGE = 100;
TextView tvPath;
TextView txtHaut;
ImageView preview;
File destination;
String imagePath;
ImageButton takePhoto;
Button btnCreate;
int serverResponseCode = 0;
ProgressDialog dialog = null;
String upLoadServerUri = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.nouvelle_annonce_step3);
// Change color of action bar
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#0099CC")));
preview = (ImageView) findViewById(R.id.nouvelle_annonce_step3_phototaken_preview);
btnCreate = (Button) findViewById(R.id.nouvelle_annonce_step3_btn) ;
txtHaut = (TextView) findViewById(R.id.nouvelle_annonce_step3_texteHaut);
takePhoto = (ImageButton) findViewById(R.id.nouvelle_annonce_choose_image);
preview.setVisibility(View.GONE);
upLoadServerUri = "http://mywebsite.com/database/PDO/uploadFile.php";
String name = dateToString(new Date(),"yyyy-MM-dd-hh-mm-ss");
destination = new File(Environment.getExternalStorageDirectory(), name + ".jpg");
takePhoto.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(destination));
startActivityForResult(intent, REQUEST_IMAGE);
}
});
btnCreate.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(New_annonce_act_step3.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
uploadFile(imagePath);
}
}).start();
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if( requestCode == REQUEST_IMAGE && resultCode == Activity.RESULT_OK ){
try {
preview.setVisibility(View.VISIBLE);
takePhoto.setVisibility(View.GONE);
txtHaut.setText("Cette image est parfaite !");
FileInputStream in = new FileInputStream(destination);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 10;
imagePath = destination.getAbsolutePath();
Log.d("INFO", "PATH === " +imagePath);
//tvPath.setText(imagePath);
Bitmap bmp = BitmapFactory.decodeStream(in, null, options);
preview.setImageBitmap(bmp);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
else{
tvPath.setText("Request cancelled");
}
}
public String dateToString(Date date, String format) {
SimpleDateFormat df = new SimpleDateFormat(format);
return df.format(date);
}
public int uploadFile(String sourceFileUri) {
String fileName = sourceFileUri;
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);
if (!sourceFile.isFile()) {
dialog.dismiss();
Log.e("uploadFile", "Source File not exist :" +imagePath);
return 0;
}
else
{
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
// 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.i("uploadFile", "HTTP Response is : "+ serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(New_annonce_act_step3.this, "File Upload Complete.",
Toast.LENGTH_SHORT).show();
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(New_annonce_act_step3.this, "MalformedURLException",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(New_annonce_act_step3.this, "Got Exception : see logcat ",
Toast.LENGTH_SHORT).show();
}
});
Log.e("Upload file to server Exception", "Exception : "
+ e.getMessage(), e);
}
dialog.dismiss();
return serverResponseCode;
} // End else block
}
}
And here is the PHP script :
<?php
$file_path = "uploads/";
$file_path = $file_path . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $file_path)) {
echo "success";
} else{
echo "fail";
}
?>
Have you verified that the user apache
(or whichever user php is running as) has permissions to write to the directory specified in $file_path
?
Put the following code in the same directory as your PHP script is, and then visit it in your web browser.
<?php
$file_path = 'uploads/';
$success = file_put_contents($file_path . "afile", "This is a test");
if($success === false) {
echo "Couldn't write file";
} else {
echo "Wrote $success bytes";
}
?>
Does this give a success message or an error message?
If it gives an error message, trying changing the ownership of the uploads
directory.
这篇关于安卓:上传到PHP服务器映像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!