我正在使用HTTPUrlConnection将图像发送到服务器。如何编写PHP代码来接收图像并发送没有json的响应。你能解释一下php如何在没有json结构的情况下接收文件数据。
public void uploadFile(String sourceFileUri, String upLoadServerUri) {
URL url=null;
HttpURLConnection connection = null;
Bitmap bm = BitmapFactory.decodeFile(sourceFileUri);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 10, bao);
try {
//Create connection
url = new URL(upLoadServerUri);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.setRequestProperty("Content-Language", "en-US");
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream writer = new DataOutputStream(connection.getOutputStream());
writer.writeBytes(bao.toString());
writer.flush();
writer.close();
//Get Response
InputStream is = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
String line;
StringBuffer response = new StringBuffer();
while ((line = rd.readLine()) != null) {
response.append(line);
response.append('\r');
}
rd.close();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
答案 0 :(得分:2)
这是我正在运行的代码。 //机器人
String sourceFileUri = Environment.getExternalStorageDirectory()+"filename.jpeg";
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()) {
return null;
}
String fullpath = "";
fullpath = sourceFile + "";
Log.e("fullpath", fullpath);
try {
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFileUri);
Log.e("fileinputstream", "" + fileInputStream);
URL url = new URL("abc.com/upload.php");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
// int lenghtOfFile = conn.getContentLength();
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("bill", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"bill\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
// create a buffer of maximum size
bytesAvailable = fileInputStream.available();
Log.e("" + bytesAvailable, "BytesAvailable");
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
Log.e("" + buffer, "Buffer");
// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
// long total = 0;
Log.e("" + bytesRead, "BytesRead");
while (bytesRead > 0) {
// total += count;
// publishProgress("" + (int) ((total * 100) /
// lenghtOfFile));
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)
String serverResponseMessage = conn.getResponseMessage();
Log.e("Server Response code", "" + serverResponseCode);
if (serverResponseMessage == "sucess") {
System.out.println("file uploaded");
}
// close the streams //
fileInputStream.close();
dos.flush();
dos.close();
} catch (Exception e) {
Log.d("error", e.getMessage());
}
// PHP
<?php
if (is_uploaded_file($_FILES['bill']['tmp_name'])) {
$name="filename";
$tmp_name = $_FILES['bill']['tmp_name'];
$pic_name = $_FILES['bill']['name'];
$ext = explode('.',$pic_name);
$extension = $ext[1];
if($extension=='png'){
unlink( $name.'.jpg');
}
if($extension=='jpg'){
unlink( $name.'.png');
}
move_uploaded_file($tmp_name, $name.'.'.$extension );
echo "sucess";
}
else{
echo "File not uploaded successfully.";
}
?>