大概
这里我弄了上传图片当做例子
目录结构
这里这几个jar包自己导入就行,第三个是一个大神写的框架,直接搜就能搜到
Android代码:
HttpUtil.java
public class HttpUtil {
public static Platform mPlatform=Platform.get();
public static void upLoadSingleFile(File file,String url){
Log.i("filePath",file.getAbsolutePath());
Log.i("fileName",file.getName());
if(file.exists()){
OkHttpClient okHttpClient=new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS).build();
//MediaType为全部类型
final MediaType mediaType=MediaType.parse("application/octet-stream");
//根据文件类型,将File装进RequestBody中
RequestBody fileBody=RequestBody.create(mediaType,file);
//将fileBody添加进MultipartBody
final RequestBody requestBody=new MultipartBody.Builder()
.addFormDataPart("file",file.getName(),fileBody)
.build();
//Request请求对象
Request request=new Request.Builder()
.post(requestBody)
.url(url)
.build();
Call call=okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
mPlatform.execute(new Runnable() {
@Override
public void run() {
Log.i("error","错误 ");
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
ResponseBody responseBody=null;
responseBody=response.body();
final String info = responseBody.string();
mPlatform.execute(new Runnable() {
@Override
public void run() {
Log.i("success",info);
}
});
}
});
}else{
Log.i("error","文件不存在!");
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Button button; //选择图片按钮
private Button button2;//上传按钮
String fileurl="";
//声明一个权限数组
String[] permissions = new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.CAMERA,
Manifest.permission.READ_EXTERNAL_STORAGE};
List<String> mPermissionList = new ArrayList<>();
private static final int PERMISSION_REQUEST = 1;
private Platform mPlatform;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initPermission();//获取权限
mPlatform=Platform.get();
init();
}
private void init() {
//初始化按钮及其点击事件
button=findViewById(R.id.upload_activity_bt_img);
button2=findViewById(R.id.btn_select);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i("button","11111");
uploadTextFile();
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_PICK); //打开相册选择图片
intent.setType("image/*");
startActivityForResult(intent,1); // 第二个参数是请求码
}
});
}
//上传
private void uploadTextFile() {
Log.i("file",fileurl); //看一下路径是否正确
File file=new File(fileurl);
//要请求的地址,testServlet下面会给出
String url="http://10.152.4.162:8080/upload/testServlet";
HttpUtil.upLoadSingleFile(file,url);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 1: // 请求码
fileurl=parseUri(data);
Log.i("file",fileurl);
break;
default:
}
}
//得到选中图片地址
public String parseUri(Intent data) {
Uri uri=data.getData();
String imagePath;
// 第二个参数是想要获取的数据
Cursor cursor = getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA},
null, null, null);
if (cursor == null) {
imagePath = uri.getPath();
} else {
cursor.moveToFirst();
int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
imagePath = cursor.getString(index);
cursor.close();
}
return imagePath; // 返回图片地址
}
//下面是动态申请权限,6.0后读写权限需要动态申请
private void initPermission(){
mPermissionList.clear();
/**
* 判断哪些权限未授予
*/
for (int i = 0; i < permissions.length; i++) {
if (ContextCompat.checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
mPermissionList.add(permissions[i]);
}
}
/**
* 判断是否为空
*/
if (mPermissionList.isEmpty()) {
//未授予的权限为空,表示都授予了
} else {
//请求权限方法
String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
ActivityCompat.requestPermissions(MainActivity.this, permissions, PERMISSION_REQUEST);
}
}
/**
* 响应授权
* 这里不管用户是否拒绝,都进入首页,不再重复申请权限
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case PERMISSION_REQUEST:
break;
default:
break;
}
}
protected void onDestroy() {
super.onDestroy();
Handler handler=new Handler(Looper.getMainLooper());
handler.removeCallbacksAndMessages(null);
}
}
布局文件(很简单,就两个按钮)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.MainActivity">
<Button
android:id="@+id/btn_select"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="选择文件"/>
<Button
android:id="@+id/upload_activity_bt_img"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="点击上传"/>
</LinearLayout>
配置文件(不要忘了添加一下权限)
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
本地服务器端
######TestServlet.java
@WebServlet(name = "TestServlet",urlPatterns = "/testServlet")
public class TestServlet extends HttpServlet {
private ServletFileUpload mServletFileUpload;
private void initUp() {
if (null == mServletFileUpload) {
File file = (File) getServletContext().getAttribute("javax.servlet.context.tempdir");
mServletFileUpload = new ServletFileUpload(new DiskFileItemFactory(
DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD, file
));
mServletFileUpload.setFileSizeMax(1024L * 1024 * 100);
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
System.out.println("开始处理请求。。。");
initUp();
response.setHeader("Content-Type", "text/html;charset=utf-8");//指定编码
Map<String, List<FileItem>> fileItemListMap = mServletFileUpload.parseParameterMap(request);
for (Map.Entry<String, List<FileItem>> entry : fileItemListMap.entrySet()) {
List<FileItem> fileItemList = entry.getValue();
if (!fileItemList.isEmpty()) {
for (FileItem fileItem : fileItemList) {
if (!fileItem.isFormField()) {//取非表单属性 ,也就是文件
String fileName = FilenameUtils.getName(new String(fileItem.getName().getBytes(), "utf-8"));
InputStream inputStream = fileItem.getInputStream();
File file = new File("D:/uploads", fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] bytes = new byte[1024 * 8];
int len;
while ((len = inputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, len);
fileOutputStream.flush();
}
fileOutputStream.close();
PrintWriter writer = response.getWriter();
writer.print(fileName + " ----> ok!!!!!");//成功 ,返回个响应
writer.flush();
}
}
}
}
System.out.println("请求处理结束。");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
效果
把手机模拟器里的 java路线.jpg 文件发送到服务器,经处理后保存到本地 D:\uploads 目录下