(亲测可用)安卓图片(文件)上传到后台,后台保存到服务器
- 以下代码实现了从安卓客户端上传图片到java后台,java后台保存图片到服务器指定地址:
- 后台(Eclipse--SpringBoot -- Controller)
- 前台(AndroidStudio -- Java)
以下代码实现了从安卓客户端上传图片到java后台,java后台保存图片到服务器指定地址:
后台(Eclipse–SpringBoot – Controller)
/**
* 接受图片
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "meal/uploadimg")
public void imgUpload(@RequestParam("file") MultipartFile file,HttpServletResponse response){
System.out.println("执行图片上传!");
//设置服务器上图片保存地址
String path = "G:/img";
File filePath = new File(path);
System.out.println("文件的保存路径:" + path);
if (!filePath.exists() && !filePath.isDirectory()) {
System.out.println("目录不存在,创建目录:" + filePath);
filePath.mkdir();
}
//获取原始文件名称(包含格式)
String originalFileName = file.getOriginalFilename();
originalFileName=originalFileName.replaceAll(",|&|=", "");
System.out.println("原始文件名称:" + originalFileName);
//获取文件类型,以最后一个`.`为标识
String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
System.out.println("文件类型:" + type);
//获取文件名称(不包含格式)
String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));
//设置文件新名称: 当前时间+文件名称(不包含格式)
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String date = sdf.format(d);
//String fileName ="a"+date + name + "." + type;
String fileName =date + "." + type;
System.out.println("新文件名称:" + fileName);
//在指定路径下创建一个文件
File targetFile = new File(path, fileName);
//将文件保存到服务器指定位置
try {
file.transferTo(targetFile);
System.out.println("上传成功");
//将文件在服务器的存储路径返回
response.setContentType("text/html;charset=utf-8");
response.getWriter().print(fileName);
} catch (IOException e) {
System.out.println("上传失败");
e.printStackTrace();
}
}
前台(AndroidStudio – Java)
使用okkttp3进行传输
需要导入的依赖(导入方法:File->Project Structure ->Dependencies–> --> ±->Search)
//数据传输
com.squareup.okhttp3:okhttp:3.4.1
com.squareup.retrofit2:retrofit:2.0.2
图片显示layout文件
<ImageView
android:id="@+id/caipu_i1"
android:layout_width="257dp"
android:layout_height="206dp"
/>
这里涉及到点击imgView弹出选择拍照或相册,我使用自定义弹窗实现的
首先在value 的styles中加入
<style name="SelectUpload">
<!--对话框背景 -->
<item name="android:windowBackground">@android:color/transparent</item>
<!--边框 -->
<item name="android:windowFrame">@null</item>
<!--没有标题 -->
<item name="android:windowNoTitle">true</item>
<!-- 是否浮现在Activity之上 -->
<item name="android:windowIsFloating">true</item>
<!--背景透明 -->
<item name="android:windowIsTranslucent">false</item>
<!-- 是否有覆盖 -->
<item name="android:windowContentOverlay">@null</item>
<!--进出的显示动画 -->
<item name="android:windowAnimationStyle">@style/normalDialogAnim</item>
<!--背景变暗-->
<item name="android:backgroundDimEnabled">true</item>
</style>
选择弹窗布局文件dialog_selectupimg.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/transparent"
android:orientation="vertical">
<Button
android:id="@+id/caipu_paizhao"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="拍照" />
<Button
android:id="@+id/caipu_xiangce"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="相册" />
<Button
android:id="@+id/caipu_quxiaoxuanze"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="取消" />
<View
android:layout_width="match_parent"
android:layout_height="15dp" />
</LinearLayout>
需要图片上传的Activity文件(caipuguanli.java)
public class caipuguanli extends AppCompatActivity {
//ImageView
private ImageView i1;
private String tupian1;
//拍照
private final int OPEN_RESULT = 1;//打开照相机
private final int CHOOSE_PICTURE = 0; //选择相册图片
private String img="";
public static final MediaType JSON=MediaType.parse("application/json; charset=utf-8");
public caipuguanli(){
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.caipu_guanli);
//实例化组件
initView();
permissiongen();
}
//组件初始化
private void initView(){
//ImageView
i1 = (ImageView)findViewById(R.id.caipu_i1);
/**
* 图片点击弹出自定义选择框
*/
i1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Dialog dialog = new Dialog(caipuguanli.this, R.style.SelectUpload);
View view = View.inflate(caipuguanli.this, R.layout.dialog_selectupimg, null);
Button paizhao = (Button)view.findViewById(R.id.caipu_paizhao);
Button xiangce = (Button)view.findViewById(R.id.caipu_xiangce);
Button quxiao = (Button)view.findViewById(R.id.caipu_quxiaoxuanze);
dialog.setContentView(view);
dialog.setCanceledOnTouchOutside(true);
//设置弹窗高度
view.setMinimumHeight((int) (ScreenSizeUtils.getInstance(caipuguanli.this).getScreenHeight() * 0.23f));
Window dialogWindow = dialog.getWindow();
WindowManager.LayoutParams lp = dialogWindow.getAttributes();
//设置弹窗宽度
lp.width = (int) (ScreenSizeUtils.getInstance(caipuguanli.this).getScreenWidth() * 0.5f);
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.BOTTOM;
dialogWindow.setAttributes(lp);
//从相机拍照获得图片
paizhao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, OPEN_RESULT);
}
});
//从相册选择图片
xiangce.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");//相片类型
startActivityForResult(intent, CHOOSE_PICTURE);
}
});
//取消按钮
quxiao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.show();
}
});
/**
*选择图片后上传并显示在imgView
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
//拍照获得图片
case OPEN_RESULT:
if(resultCode == RESULT_OK){
try{
Bundle bundle = data.getExtras();
Bitmap bitmap = (Bitmap) bundle.get("data");
i1.setImageBitmap(bitmap);
//将拍照获得的bitmap转换成图片文件并保存到本地
File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis()+".jpg");
FileOutputStream fileOutStream = new FileOutputStream(file);
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutStream);
fileOutStream.flush();
fileOutStream.close();
uploadImage(file);
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
Log.d("tag",e.getMessage());
Toast.makeText(this,"程序崩溃",Toast.LENGTH_SHORT).show();
}
}
break;
//相册选择图片
case CHOOSE_PICTURE:
if(resultCode == RESULT_OK ){
try{
Uri uri = data.getData();
Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
i1.setImageBitmap(bitmap);
String path = RealPathFromUriUtils.getRealPathFromUri(this,uri);
File file = new File(path);
uploadImage(file);
} catch (Exception e) {
e.printStackTrace();
Log.d("tag",e.getMessage());
Toast.makeText(this,"程序崩溃",Toast.LENGTH_SHORT).show();
}}
break;
}
}
/**
* 上传图片,返回服务器端保存的图片名称
* @param
* @return 新图片名称
* @throws IOException
* @throws JSONException
*/
public void uploadImage(File file) {
// File file = new File(imagePath);
OkHttpClient httpClient = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/octet-stream");//设置类型,类型为八位字节流
RequestBody requestBody = RequestBody.create(mediaType, file);//把文件与类型放入请求体
MultipartBody multipartBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", file.getName(), requestBody)//文件名
.build();
Request request = new Request.Builder()
.url(caipulist.URL+"meal/uploadimg")
.post(multipartBody)
.build();
Call call = httpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
System.out.println(e);
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(caipuguanli.this,"添加失败!",Toast.LENGTH_SHORT).show();
}
});
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//在这里根据返回内容执行具体的操作
final String resdata=response.body().string();
System.out.println(resdata);
if (response.code()==200){
runOnUiThread(new Runnable() {
@Override
public void run() {
// Toast.makeText(caipuguanli.this,resdata,Toast.LENGTH_SHORT).show();
tupian1 = resdata;
}
});
}
}
});
}
}