Php 图像作为多部分上传到服务器文件夹在android中不起作用
从android gallery将图像上载到服务器文件夹不起作用。它没有任何异常,图像不会上载到文件夹。谷歌搜索了所有的示例,尝试了许多解决方案,但没有一个对我有效Php 图像作为多部分上传到服务器文件夹在android中不起作用,php,android,image,upload,Php,Android,Image,Upload,从android gallery将图像上载到服务器文件夹不起作用。它没有任何异常,图像不会上载到文件夹。谷歌搜索了所有的示例,尝试了许多解决方案,但没有一个对我有效 package net.simplifiedcoding.volleyupload; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.net.HttpURLConnection; im
package net.simplifiedcoding.volleyupload;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class UploadImageDemo extends Activity {
TextView tv;
Button b;
int serverResponseCode = 0;
ProgressDialog dialog = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button)findViewById(R.id.but);
tv = (TextView)findViewById(R.id.tv);
tv.setText("Uploading file path :- '/storage/sdcard0/DCIM/Camera/IMG_20160112_104150.jpg'");
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dialog = ProgressDialog.show(UploadImageDemo.this, "", "Uploading file...", true);
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
tv.setText("uploading started.....");
}
});
int response= uploadFile("/storage/sdcard0/DCIM/Camera/IMG_20160112_104150.jpg");
}
}).start();
}
});
}
public int uploadFile(String sourceFileUri) {
String upLoadServerUri = "http://appsinbox.com/appstimesheetnew/testup.php";
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()) {
Log.e("uploadFile", "Source File Does not exist");
return 0;
}
try { // open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP connection to the URL
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);
bytesAvailable = fileInputStream.available(); // create a buffer of maximum size
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();
final String serverResponseMessage = conn.getResponseMessage();
Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
if(serverResponseCode == 200){
runOnUiThread(new Runnable() {
public void run() {
tv.setText("File Upload Completed.");
}
});
}
//close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
dialog.dismiss();
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
dialog.dismiss();
e.printStackTrace();
}
dialog.dismiss();
return serverResponseCode;
}
}
下面是php代码
$target_path1 = "/var/www/vhosts/logineduhub.com/appsinbox/appstimesheetnew/uploads/";
/* Add the original filename to our target path. Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename($_FILES['uploaded_file']['name']);
if( chmod($target_path1, 0777) ) {
// more code
chmod($target_path1, 0755);
if (move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1))
{
echo "hi";
echo "The first file " . basename($_FILES['uploaded_file']['name']) . " has been uploaded.";
}
else {
echo "bye";
echo "There was an error uploading the file, please try again!";
echo "filename: " . basename($_FILES['uploaded_file']['name']);
echo "target_path: " . $target_path1;
}
}
else
{
echo "Couldn't do it.";
}
我就是这样做的(或多或少:)
安卓:
public String uploadFile(String u, String imageFilePath, String filename) {
String attachmentName = "image";
String attachmentFileName = filename + ".jpg";
String crlf = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
StringBuffer response = new StringBuffer();
try {
FileInputStream fileInputStream = new FileInputStream(imageFilePath);
try {
HttpURLConnection httpUrlConnection = null;
URL url = new URL(u);
httpUrlConnection = (HttpURLConnection) url.openConnection();
httpUrlConnection.setUseCaches(false);
httpUrlConnection.setDoOutput(true);
httpUrlConnection.setRequestMethod("POST");
httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
httpUrlConnection.setRequestProperty("Cache-Control", "no-cache");
httpUrlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
DataOutputStream request = new DataOutputStream(httpUrlConnection.getOutputStream());
request.writeBytes(twoHyphens + boundary + crlf);
request.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + crlf);
request.writeBytes(crlf);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
request.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
request.writeBytes(crlf);
request.writeBytes(twoHyphens + boundary + twoHyphens + crlf);
request.flush();
request.close();
int responseCode = httpUrlConnection.getResponseCode();
String inputLine = "";
if (responseCode == 200) {
BufferedReader in = new BufferedReader(
new InputStreamReader(httpUrlConnection.getInputStream()));
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
}
} catch (MalformedInputException e) {
Log.v("Err", e.getMessage());
} catch (ConnectException e) {
Log.v("Err", e.getMessage());
} catch (UnknownHostException e) {
Log.v("Err", e.getMessage());
} catch (Exception e) {
Log.v("Err", e.getMessage());
}
} catch (FileNotFoundException e) {
Log.v("Err", e.getMessage());
}
return response.toString();
}
和php
<?php
define('DS',DIRECTORY_SEPARATOR);
$response = 0;
if($_FILES){
if(!$_FILES['image']['error']){
if(is_uploaded_file($_FILES['image']['tmp_name'])){
$dirpath = 'path to save file';
if(!is_dir($dirpath)){
mkdir($dirpath,0777);
}
$destination = $dirpath.DS.$_FILES['image']['name'];
if(move_uploaded_file($_FILES['image']['tmp_name'], $destination)){
$response = 1;
}
}
}
}
echo $response;
?>
logcat中有什么东西吗?你在主线程上进行联网,这不是正确的方式。对于android部分,你可以使用毕加索库在logcat@Egorjust上上传imageNothing。这是一个建议!尝试使用截击,它更简单、更快!您是否向清单中添加了internet权限?