android studio如何实现上传图片到java服务器
作者:小确幸
时间:2023-04-24
来源:互联网
浏览:0
1.build.gradle配置(增加)dependencies{implementation'com.squareup.okhttp3:okhttp:4.9.0'implementation'org.conscrypt:conscrypt-android:2.5.1'}2.AndroidManifest.xml配置权限在application里面添加android:usesCleartextTraffic="true"3.安卓前端部分3.1xml样式界面3.2安卓后台代码
1.build.gradle配置(增加)
dependencies{
implementation 'com.squareup.okhttp3:okhttp:4.9.0'
implementation 'org.conscrypt:conscrypt-android:2.5.1'
}2.AndroidManifest.xml配置权限
在application里面添加android:usesCleartextTraffic="true"
3.安卓前端部分
3.1xml样式界面
3.2安卓后台代码MainActivity
package com.example.upload;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
private Button btn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String result = "{\"data\": \"0\"}";
new Thread(new Runnable(){
@Override
public void run() {
String img = Environment.getExternalStorageDirectory()+"/1/123456789.png";
String url = "http://192.168.0.103:8019/uploadAudio";
try {
uploadImage(url,img);
} catch (IOException e) {
Looper.prepare();
e.printStackTrace();
Looper.loop();
} catch (JSONException e) {
e.printStackTrace();
}
//创建信息对象
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("data",result);
message.setData(bundle);//向主线程发信息
addTrackHandler.sendMessage(message);
}
}).start();
}
});
}
/**
* 上传图片
* @param url
* @param imagePath 图片路径
* @return 新图片的路径
* @throws IOException
* @throws JSONException
*/
public static String uploadImage(String url, String imagePath) throws IOException, JSONException {
OkHttpClient okHttpClient = new OkHttpClient();
File file = new File(imagePath);
RequestBody image = RequestBody.create(MediaType.parse("image/png"), file);
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", imagePath, image)
.build();
Request request = new Request.Builder()
.url(url)
.post(requestBody)
.build();
Response response = okHttpClient.newCall(request).execute();
JSONObject jsonObject = new JSONObject(response.body().string());
return jsonObject.optString("image");
}
Handler addTrackHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message message) {
String result = "";
try {
result = message.getData().getString("data");
Toast.makeText(MainActivity.this, "新增成功", Toast.LENGTH_SHORT).show();
}catch (Exception e){
}
//Toast.makeText(MainActivity.this, "调用成功"+result, Toast.LENGTH_SHORT).show();//测试弹框
return true;
}
});
}4.spring boot后台接受图片并写入本地路径
@RequestMapping("/uploadAudio")
@ResponseBody
public void uploadAudio(@RequestParam MultipartFile file) {
System.out.println(file.getOriginalFilename());
if (!file.isEmpty()) {
String filename = file.getOriginalFilename();
System.out.println("Load fn:" + filename);
try {
String fileurl = "d:/Download/testt.png";
File f = new File(fileurl);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(f));
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
out.write(file.getBytes());
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}else {
System.out.println("上传失败,因为文件是空的.");
}
}注:如果上传图片提示没有权限,则长按apk图标,打开读取本地文件的权限即可
作者最新文章
Windows 10
2026-09-16 17:44
Python安装后怎么打开:使用IDLE或命令行启动解释器
2026-09-16 13:54
Windows系统Python安装教程:下载、勾选PATH及环境变量配置
2026-09-16 13:53
“等灯不计时”落地解析:算法善意如何转化为技术能力与生态协同
2026-09-08 18:03
英伟达推出NVHBM:定制HBM带宽提升30%并扩展NVLink Fusion生态
2026-09-08 17:31
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多
Windows 10
Windows
Windows 10 是一款微软推出的经典操作系统,拥有硬件兼容性与多任务处理能力。它更偏向把系统状态查看和常用调节动作放在一起,适合需要持续观察和微调设备状态的场景。
极度公式
Windows/macOS/Linux
极度公式是一款跨平台专业LaTeX公式识别编辑软件,支持OCR公式识别和多平台编辑。和使用说明,避免使用,享受完整功能与稳定支持。做扫描整理、文字提取和表格转换时,它能把识别后的处理步骤接得更顺,资料录入这类场景会省下不少时间。
















