安卓文件上传到php (你知道如何将安卓文件上传到php吗?)
在安卓开发中,经常需要将一些生成的文件上传到服务器,这时就需要涉及到文件上传的问题。对于PHP开发者来说,在实现文件上传功能时,需要使用到 PHP 的函数库和特殊的写法,为此本文将会介绍一下如何将安卓文件上传到PHP。
文件上传的原理
文件上传的基本原理是:客户端(如浏览器)将文件数据发送到服务器,服务器调用相关函数将获取到的数据存储到指定目录中。在安卓中,也需要使用这个基本原理进行文件上传。
安卓文件上传的具体步骤如下:
- 客户端选取要上传的文件,将其转换成字节流的形式并压缩为 zip 格式。
- 客户端连接服务器,将上传数据以字节数组的形式发送到服务器。
- 服务器端根据表单值读取并写入文件。
上传文件的代码实现
以下是安卓文件上传的核心代码,通过这个代码你可以将文件上传到PHP服务器:
public void uploadFile(String pathToOurFile)
{
try {
// Set your file path here
FileInputStream fstrm = new FileInputStream(pathToOurFile);
// Set your server page url (and the file title/description)
HttpFileUploader htfu = new HttpFileUploader("http://your-php-server/upload.php", "my file title","my file description");
htfu.doStart(fstrm);
} catch (FileNotFoundException e) {
// Error: File not found
}
}
其中的 HttpFileUploader
类封装了安卓端到 PHP 服务器端的文件上传的一些关键操作。下面是 HttpFileUploader
的代码实现:
“`
public class HttpFileUploader{
URL connectURL;
String responseString;
String Title;
String Description;
byte[ ] dataToServer;
FileInputStream fileInputStream = null;
public HttpFileUploader(String urlString, String title, String description){
try{
connectURL = new URL(urlString);
Title= title;
Description = description;
}catch(Exception ex){
Log.i(“HttpFileUploader”,”URL Malformatted”);
}
}
public void doStart(FileInputStream stream){
fileInputStream = stream;
thirdTry();
}
private void thirdTry() {
String path= Title + Description;
String res= path.replaceAll(“[^\w\.\s-]”, “”);
try{
fileInputStream = new FileInputStream(new File(path) );
Log.d(“HttpFileUploader”, “Opening Connection”);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod(“POST”);
conn.setRequestProperty(“Connection”, “Keep-Alive”);
conn.setRequestProperty(“Content-Type”, “multipart/form-data;boundary=*“);
DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes("--*****\r\n");
dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + path + "\"\r\n");
dos.writeBytes("\r\n");
Log.d("HttpFileUploader", "Headers are written");
int bytesAvailable = fileInputStream.available();
int bufferSize = Math.min(bytesAvailable, 1048576);
byte[] buffer = new byte[bufferSize];
int bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
dos.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, 1048576);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
// Close the streams
fileInputStream.close();
dos.writeBytes("\r\n");
dos.writeBytes("--*****\r\n");
dos.flush();
dos.close();
}catch (Exception ex){
Log.d("HttpFileUploader","Error: " + ex.getMessage(), ex);
}
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.d("HttpFileUploader", "Response: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.d("HttpFileUploader", "Error: " + ioex.getMessage(), ioex);
}
}
}
“`
在这个类中需要注意以下几点:
HttpFileUploader
类需要重载一个构造函数,来传具体的参数值(服务器(PHP)地址,文件title和描述等)。doStart()
函数是触发上传的方法。如果上传成功,则会打印 HTTP 响应的 body 内容。setRequestProperty()
为HttpServletRequest 手动设置HTTP请求头,至少需要设置 Content-Type 字段,值为 multipart/form-data。
在 PHP 代码方面,需要针对上述代码中的 connectURL
。使用 PHP 接收文件上传需要在服务器端的 PHP 文件中添加以下代码段:
“`
$target_path = “/uploads/”; //your target upload directory
$targetpath = $targetpath . basename( $_FILES[‘uploadedfile’][‘name’]);
if(moveuploadedfile($FILES[‘uploadedfile’][‘tmpname’], $targetpath)) {
echo “The file “. basename( $FILES[‘uploadedfile’][‘name’]).
” has been uploaded”;
} else{
echo “There was an error uploading the file, please try again!”;
}
“`
上述代码先定义了上传文件保存目录,然后根据表单中的 “uploadedfile” 值来获取上传的文件并移动到指定目录中,最后输出相关提示信息。
关于文件上传的安全性
在进行文件上传时,请务必确保上传的文件不包含恶意代码。此外,在服务器端也要针对上传的文件进行安全性校验,以确保上传文件能够通过上传检测且存储在非web目录下。因为 PHP 文件的解析能力,上传目录如果在web目录下时,可能会被恶意代码拿来直接执行,从而破坏服务器的安全性。
总结
如何将安卓文件上传到PHP?本文基本上已经讲解清楚了。在安卓端的实现中,上传文件的核心代码是 HttpFileUploader
类,这个类主要负责链接服务器和将文件数据发送给服务器。在后端PHP代码的实现中,主要负责文件上传目录的处理、安全性校验和相关提示信息的输出。