前端开发
1. 创建上传界面
首先,在Android项目中创建一个简单的上传界面。可以使用EditText和Button来实现。
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/image_path"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入图片路径" />
<Button
android:id="@+id/upload_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="上传图片"
android:layout_below="@id/image_path" />
</RelativeLayout>
2. 图片选择和上传
Button uploadButton = findViewById(R.id.upload_button);
uploadButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1 && resultCode == RESULT_OK) {
Uri uri = data.getData();
String path = uri.getPath();
uploadImage(path);
}
}
private void uploadImage(String imagePath) {
HttpURLConnection connection = null;
try {
URL url = new URL("http://yourserver.com/upload");
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data");
connection.setDoOutput(true);
OutputStream os = connection.getOutputStream();
FileInputStream fis = new FileInputStream(imagePath);
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) != -1) {
os.write(buffer, 0, length);
}
fis.close();
os.close();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
// 图片上传成功
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
后端开发
1. 创建ThinkPHP控制器
<?php
namespace app\index\controller;
use think\Controller;
class Upload extends Controller
{
public function index()
{
// 获取上传的图片
$file = request()->file('image');
if ($file) {
$info = $file->move('public/uploads');
if ($info) {
// 上传成功
return json(['code' => 0, 'msg' => '上传成功', 'data' => ['path' => $info->getSaveName()]]);
} else {
// 上传失败
return json(['code' => 1, 'msg' => $file->getError()]);
}
} else {
// 没有上传的图片
return json(['code' => 2, 'msg' => '没有上传的图片']);
}
}
}
2. 配置上传目录
3. 配置路由
在route/route.php
文件中添加路由规则。
use think\facade\Route;
Route::post('upload', 'index/Upload/index');