Php 在HttpUrlConnection中发送数据和图像
我知道这个问题在这个网站上已经被问过好几次了,但我找不到正确的方法来解决 我想使用Php 在HttpUrlConnection中发送数据和图像,php,android,httpurlconnection,Php,Android,Httpurlconnection,我知道这个问题在这个网站上已经被问过好几次了,但我找不到正确的方法来解决 我想使用HTTPURLCONNECTION和PHP将一个文件从android上传到服务器 我发现了一个关于它的教程,但只是在发送文件时没有数据,数据包括文件名、详细信息/说明和注释 FileInputStream fileInputStream = new FileInputStream(sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP co
HTTPURLCONNECTION
和PHP
将一个文件从android上传到服务器
我发现了一个关于它的教程,但只是在发送文件时没有数据,数据包括文件名、详细信息/说明和注释
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);
conn.setRequestProperty("Filename","testfilename");
JSONObject cred = new JSONObject();
cred.put("name","juan");
cred.put("password","pass");
dos = new DataOutputStream(conn.getOutputStream());
// for every param
dos.writeBytes("Content-Disposition: form-data; name=\"chunk\"" + lineEnd);
dos.writeBytes("Content-Type: text/plain; charset=UTF-8" + lineEnd);
dos.writeBytes("Content-Length: " + cred.length() + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(cred.toString() + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
/**Create file*/
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes (cred.toString());
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd); //close the streams //
fileInputStream.close();
dos.flush();
dos.close();
PHP:
尝试在日志cat中打印响应,结果如下:
HTTP响应为:name-fail您没有选择要上载的文件。
我应该如何做才能正确完成
感谢您的帮助。我已经使用php在服务器上发送了包含其他信息的图像文件。代码如下。这是在服务器上上传文件的一种非常简单的方法。我使用了multypartentity
// ************** Report Crime ******************
public String reportCrime(String uploadFile, int userid, int crimetype,
String crimedetails, String lat, String longi, String reporteddate,
Integer language) {
String url;
MultipartEntity entity;
try {
url = String.format(Constant.SERVER_URL
+ "push_notification/reportCrime.php"); // url of your webservice
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//uploadfile is a path of the image.
File file = new File(uploadFile);
if (!file.equals("Image not Provided.")) {
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(uploadFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg",
uploadFile);
// FileBody image = new FileBody(file, "image/jpeg");
entity.addPart("Image", foto);
}
} else {
FormBodyPart image = new FormBodyPart("Image", new StringBody(
""));
entity.addPart(image);
}
FormBodyPart userId = new FormBodyPart("userId", new StringBody(
String.valueOf(userid)));
entity.addPart(userId);
FormBodyPart crimeType = new FormBodyPart("crimetype",
new StringBody(String.valueOf(crimetype)));
entity.addPart(crimeType);
FormBodyPart lanaguagetype = new FormBodyPart("InputLang",
new StringBody(String.valueOf(language.toString())));
entity.addPart(lanaguagetype);
FormBodyPart crimeDetails = new FormBodyPart("crimedetail",
new StringBody(crimedetails));
entity.addPart(crimeDetails);
FormBodyPart latittude = new FormBodyPart("latittude",
new StringBody(lat));
entity.addPart(latittude);
FormBodyPart longitude = new FormBodyPart("longitude",
new StringBody(longi));
entity.addPart(longitude);
FormBodyPart reportedDate = new FormBodyPart("reporteddatetime",
new StringBody(reporteddate));
entity.addPart(reportedDate);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return "error";
}
HttpParams httpParams = new BasicHttpParams();
HttpContext httpContext = new BasicHttpContext();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
result = sb.toString();
} finally {
if (in != null)
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
在php端处理图像文件
$u_id = $_REQUEST['userId'];
$c_type = $_REQUEST['crimetype'];
$c_detail = $_REQUEST['crimedetail'];
$lat = $_REQUEST['latittude'];
$long = $_REQUEST['longitude'];
$Language= $_REQUEST['InputLang'];
$image = '';
$r_time = $_REQUEST['reporteddatetime'];
$address='';
if (!empty($_FILES["Image"]["tmp_name"])) {
$tmp_img = $_FILES["Image"]["tmp_name"];
$path = $_FILES["Image"]['name'];
$ext = pathinfo($path, PATHINFO_EXTENSION);
$imagename = date("YmdHis");
$image = "http://" . $_SERVER['HTTP_HOST'] . "/webservices/crime-image/" . $imagename . "." . $ext;
$dirpath = $_SERVER['DOCUMENT_ROOT'] . "/webservices/crime-image/" . $imagename . "." . $ext;
move_uploaded_file($tmp_img, $dirpath);
}
$query = mysql_query("SELECT crimeId,((ACOS(SIN($lat * PI() / 180) * SIN(`lattitude` * PI() / 180) + COS($lat * PI() / 180) * COS(`lattitude` * PI() / 180) * COS(($long-`Longitude`) * PI() / 180)) * 180 / PI()) * 60 * 1.1515) AS `distance` FROM crimes where crimeTypeId = '$c_type' and reportedDateTime between ('" . $r_time . " 00:00:00') and ('" . $r_time . " 23:59:59') HAVING `distance`<= '2'");
if (mysql_num_rows($query) > 1) {
echo 'This Crime Already Register';
} else {
$query_str = "INSERT INTO `crimes` (
`crimeId` ,
`crimeTypeId` ,
`crimeDetail` ,
`lattitude` ,
`longitude` ,
`Image` ,
`status` ,
`reportedDateTime` ,
`createdDateTime` ,
`modifiedDateTime`,
`reported_by`,
`isDeleted`,
`address`
)
VALUES (
NULL ,
'$c_type',
'$c_detail',
'$lat',
'$long',
'$image',
'0',
'$r_time',
now(),
now(),
'$u_id',
'0',
'$address'
)";
$query = mysql_query($query_str) or die(mysql_error());
$u\u id=$\u请求['userId'];
$c_type=$_请求['crimetype'];
$c_detail=$_请求['crimedeail'];
$lat=$_请求['lattude'];
$long=$_请求['longitude'];
$Language=$_请求['InputLang'];
$image='';
$r_time=$_请求['reporteddatetime'];
$address='';
如果(!empty($_FILES[“Image”][“tmp_name”]){
$tmp_img=$_文件[“图像”][“tmp_名称”];
$path=$\u文件[“图像”][“名称”];
$ext=pathinfo($path,pathinfo_扩展名);
$imagename=日期(“YmdHis”);
$image=“http://.”$\u服务器['http\u主机].“/webservices/crime image/”$imagename.“$ext;
$dirpath=$\u SERVER['DOCUMENT\u ROOT'].“/webservices/crime image/”$imagename.“$ext;
移动上传的文件($tmp\u img,$dirpath);
}
$query=mysql\u query(“选择crimeId,($ACOS(SIN($lat*PI()/180)*SIN(`latitude`*PI()/180)+COS($latitude`*PI()/180)*COS($long-`Longitude`*PI()/180))*60*1.1515)作为犯罪与犯罪的距离,其中crimeTypeId=$c\u type和报告的日期时间介于(“$r\u time.”00:00:00')和(”.$r_time.“23:59:59”)使用“distance”尝试使用该库。这将减少大量代码,并且是一个单一类库。只需将HttpRequest.java复制到项目中。这就是上载图像和一些数据的方式
HttpRequest request = HttpRequest.post("http://google.com");
request.part("status[body]", "Making a multipart request");//this is data
request.part("status[image]", new File("/home/kevin/Pictures/ide.png"));//this is your image
if (request.ok())
System.out.println("Upload success");
顺便说一句,你肯定已经找到了解决方案,我给出了答案,问题来自php文件。下面是我用来将图片从android下载到php的一个:
if(isset($_FILES['uploadedfile']))
{
$ok = fwrite($ouverture, 'isset ok'.PHP_EOL);
$dossier = 'profilesPictures/';
$ok = fwrite($ouverture, $_FILES['uploadedfile']['name'].PHP_EOL);
$ok = fwrite($ouverture, $_FILES['uploadedfile']['tmp_name'].PHP_EOL);
$fichier = basename($_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $dossier . $fichier))
{
// OK
}
else
{
// NOK
}
}
name
和tmp\u name
字段是固定的,因此您不能使用其他您没有使用fileInputStream
加-
dos.write([bytearray from file]);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.write([bytearray from file]);
dos.writeBytes(crlf);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);