对于想了解将图片从Android上传到PHP服务器的读者,本文将提供新的信息,我们将详细介绍安卓导入图片,并且为您提供关于android–如何从字节数组上传数据到PHP服务器上传进度?、android
对于想了解将图片从Android上传到PHP服务器的读者,本文将提供新的信息,我们将详细介绍安卓导入图片,并且为您提供关于android – 如何从字节数组上传数据到PHP服务器上传进度?、android 上传图片到php服务器、android-将图片从SDCard上传到FaceBook、Android上传到packageCloud的有价值信息。
本文目录一览:- 将图片从Android上传到PHP服务器(安卓导入图片)
- android – 如何从字节数组上传数据到PHP服务器上传进度?
- android 上传图片到php服务器
- android-将图片从SDCard上传到FaceBook
- Android上传到packageCloud
将图片从Android上传到PHP服务器(安卓导入图片)
我正在尝试从Android设备将文件上传到php服务器。有相同问题的话题,但他使用的是不同的方法。我的Android辅助代码运行正常,并且未显示任何错误消息,但服务器未收到任何文件。这是我的示例代码,我在网上找到了。
import java.io.FileInputStream;import android.app.Activity;import android.os.Bundle;import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.File;import java.io.IOException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import android.util.Log;public class uploadfile extends Activity {/** Called when the activity is first created. */@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); doFileUpload();}private void doFileUpload(){HttpURLConnection conn = null;DataOutputStream dos = null;DataInputStream inStream = null; String exsistingFileName = "/sdcard/def.jpg";// Is this the place are you doing something wrong.String lineEnd = "rn";String twoHyphens = "--";String boundary = "*****";int bytesRead, bytesAvailable, bufferSize;byte[] buffer;int maxBufferSize = 1*1024*1024;String responseFromServer = "";String urlString = "http://192.168.1.6/index.php";try { //------------------ CLIENT REQUEST Log.e("MediaPlayer","Inside second Method"); FileInputStream fileInputStream = new FileInputStream(new File(exsistingFileName) ); // open a URL connection to the Servlet URL url = new URL(urlString); // Open a HTTP connection to the URL conn = (HttpURLConnection) url.openConnection(); // Allow Inputs conn.setDoInput(true); // Allow Outputs conn.setDoOutput(true); // Don''t use a cached copy. conn.setUseCaches(false); // Use a post method. conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary); dos = new DataOutputStream( conn.getOutputStream() ); dos.writeBytes(twoHyphens + boundary + lineEnd); dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + exsistingFileName + "\"" + lineEnd); dos.writeBytes(lineEnd); Log.e("MediaPlayer","Headers are written"); // 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); // close streams Log.e("MediaPlayer","File is written"); fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { Log.e("MediaPlayer", "error: " + ex.getMessage(), ex); } catch (IOException ioe) { Log.e("MediaPlayer", "error: " + ioe.getMessage(), ioe); } //------------------ read the SERVER RESPONSE try { inStream = new DataInputStream ( conn.getInputStream() ); String str; while (( str = inStream.readLine()) != null) { Log.e("MediaPlayer","Server Response"+str); } inStream.close(); } catch (IOException ioex){ Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex); } } }
和我的PHP服务器端代码如下
<?php $target_path = "uploads/"; $target_path = $target_path . basename( $_FILES[''uploadedfile''][''name'']); if(move_uploaded_file($_FILES[''uploadedfile''][''tmp_name''], $target_path)) {echo "The file ". basename( $_FILES[''uploadedfile''][''name'']). " has been uploaded"; } else{ echo "There was an error uploading the file, please try again!"; } ?>
Apache正在运行。当我运行服务器时,出现此错误消息。上传文件时出错,请重试!我已经在eclipse中检查了日志数据,我认为是套接字问题,但是我不确定。如果有人知道解决方案,请提供帮助。
11-28 05:37:55.310: DEBUG/SntpClient(59): request time failed: java.net.SocketException: Address family not supported by protocol
答案1
小编典典似乎服务器没有响应客户端。尝试通过Android应用程序使用ftp连接进行上传,如果可以的话,请检查您的Apache配置是否接受连接和可写目录。当我遇到类似的问题时,事实证明我的目录没有写权限。
是来自Java还是来自Apache的错误?
android – 如何从字节数组上传数据到PHP服务器上传进度?
http://loopj.com/android-async-http/
我想要的是在进度条上显示已上载字节数组的字节数.现在,问题是,如何在上传进行过程中了解已上传的字节数.需要有关想法/示例/代码问题的帮助.先谢谢你们.
解决方法
class ImageUploadTask extends AsyncTask<Void,Void,String> { @Override protected void onPreExecute() { pb.setVisibility(View.VISIBLE); } @Override protected String doInBackground(Void... unused) { String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; try { FileInputStream fileInputStream = 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=\"image\";filename=\"" + pathToOurFile +"\"" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); Log.v("Size",bytesAvailable+""); pb.setProgress(0); pb.setMax(bytesAvailable); //Log.v("Max",pb.getMax()+""); bufferSize = Math.min(bytesAvailable,maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer,bufferSize); while (bytesRead > 0) { outputStream.write(buffer,bufferSize); bytesAvailable = fileInputStream.available(); Log.v("Available",bytesAvailable+""); publishProgress(); bufferSize = Math.min(bytesAvailable,maxBufferSize); bytesRead = fileInputStream.read(buffer,bufferSize); } outputStream.writeBytes(lineEnd); outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) serverResponseCode = connection.getResponseCode(); serverResponseMessage = connection.getResponseMessage(); System.out.println(serverResponseMessage); fileInputStream.close(); outputStream.flush(); outputStream.close(); } catch (Exception ex) { //Exception handling } //publishProgress(); return null; } @Override protected void onProgressUpdate(Void... unsued) { super.onProgressUpdate(unsued); pb.setProgress(pb.getMax()-bytesAvailable); } @Override protected void onPostExecute(String sResponse) { //if(pb.getProgress()>= pb.getMax()) pb.setVisibility(View.INVISIBLE); } }
android 上传图片到php服务器
android代码
public class EX08_11 extends Activity
{
/* 变量声明
* newName:上传后在服务器上的文件名称
* uploadFile:要上传的文件路径
* actionUrl:服务器对应的程序路径 */
// private String newName="345444.jpg";
private String uploadFile="/sdcard/345444.jpg";
private String acti//*********/upload.php";
private TextView mText1;
private TextView mText2;
private Button mButton;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mText1 = (TextView) findViewById(R.id.myText2);
mText1.setText("文件路径:\n"+uploadFile);
mText2 = (TextView) findViewById(R.id.myText3);
mText2.setText("上传网址:\n"+actionUrl);
/* 设定mButton的onClick事件处理 */
mButton = (Button) findViewById(R.id.myButton);
mButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
uploadFile();
}
});
}
/* 上传文件吹Server的method */
private void uploadFile()
{
// String end = "\r\n";
// String twoHyphens = "--";
String boundary = "*****";
try
{
URL url =new URL(actionUrl);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
/* 允许Input、Output,不使用Cache */
// con.setReadTimeout(5 * 1000);
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
/* 设定传送的method=POST */
con.setRequestMethod("POST");
/* setRequestProperty */
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("enctype",
"multipart/form-data;boundary="+boundary);
/* 设定DataOutputStream */
DataOutputStream ds =
new DataOutputStream(con.getOutputStream());
/*ds.writeBytes(twoHyphens + boundary + end);
ds.writeBytes("Content-Disposition: form-data; " +
"name=\"file1\";filename=\"" +
newName +"\"" + end);
ds.writeBytes(end); */
/* 取得文件的FileInputStream */
FileInputStream fStream = new FileInputStream(uploadFile);
/* 设定每次写入1024bytes */
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
立即学习“PHP免费学习笔记(深入)”;
int length = -1;
/* 从文件读取数据到缓冲区 */
while((length = fStream.read(buffer)) != -1)
{
/* 将数据写入DataOutputStream中 */
ds.write(buffer, 0, length);
}
// ds.writeBytes(end);
// ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
/* close streams */
fStream.close();
ds.flush();
/* 取得Response内容 */
InputStream is = con.getInputStream();
int ch;
StringBuffer b =new StringBuffer();
while( ( ch = is.read() ) != -1 )
{
b.append( (char)ch );
}
/* 将Response显示于Dialog */
showDialog(b.toString().trim());
/* 关闭DataOutputStream */
ds.close();
}
catch(Exception e)
{
showDialog(""+e);
}
}
/* 显示Dialog的method */
private void showDialog(String mess)
{
new AlertDialog.Builder(EX08_11.this).setTitle("Message")
.setMessage(mess)
.setNegativeButton("确定",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
}
})
.show();
}
}
php代码
$data = file_get_contents(''php://input'');
$time = date("YmdHis");
$rand = rand(0,100);
$filename = $_SERVER[''DOCUMENT_ROOT''].''/image/''.$time.$rand.''.jpg'';
while(file_exists($filename))
{
$filename = $_SERVER[''DOCUMENT_ROOT''].''/image/''.$time.rand(0,100).''.jpg'';
}
echo $filename;
$handle = fopen($filename, ''w'');
if ($handle)
{
fwrite($handle,$data);
fclose($handle);
echo "success";
}
?>
以上就介绍了android 上传图片到php服务器,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。
android-将图片从SDCard上传到FaceBook
借助Android 2.1,如何将图像上传到Facebook墙?图像存储在SDCard中.
解决方法:
您应该使用Facebook API http://developers.facebook.com/docs/guides/mobile/#android.
然后使用以下代码:
byte[] data = null;
try {
FileInputStream fis = new FileInputStream(PATH_TO_FILE);
Bitmap bi = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
} catch (FileNotFoundException e) {
e.printstacktrace();
Log.d("onCreate", "debug error e = " + e.toString());
}
Bundle params = new Bundle();
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
Facebook facebook = new Facebook(FACEBOOK_APP_ID);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
mAsyncRunner.request(null, params, "POST", new RequestListener() {
public void onMalformedURLException(MalformedURLException e, Object state) {
Log.d("request RequestListener", "debug onMalformedURLException");
}
public void onIOException(IOException e, Object state) {
Log.d("request RequestListener", "debug onIOException");
}
public void onFileNotFoundException(FileNotFoundException e, Object state) {
Log.d("request RequestListener", "debug onFileNotFoundException");
}
public void onFacebookError(FacebookError e, Object state) {
Log.d("request RequestListener", "debug onFacebookError");
}
public void onComplete(String response, Object state) {
Log.d("request RequestListener", "debug onComplete");
}
}, null);
确保您的应用程序有权访问互联网和sdcard
Android上传到packageCloud
如何解决Android上传到packageCloud?
我对PackageCloud的uploadArchives有问题。我有像两个模块库的应用程序。我像在Gradle部分的说明https://packagecloud.io/docs中一样执行所有操作,并得到如下错误:
FAILURE: Build Failed with an exception.
* What went wrong:
Execution Failed for task '':myApp:packageReleaseAssets''.
> java.lang.NullPointerException (no error message)
如何解决此错误?我到处搜索,没有找到解决方法。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)
我们今天的关于将图片从Android上传到PHP服务器和安卓导入图片的分享已经告一段落,感谢您的关注,如果您想了解更多关于android – 如何从字节数组上传数据到PHP服务器上传进度?、android 上传图片到php服务器、android-将图片从SDCard上传到FaceBook、Android上传到packageCloud的相关信息,请在本站查询。
本文标签: