實(shí)現(xiàn)將本地存儲的圖片發(fā)送到后臺
使用springMVC框架蚪腋,獲取本地圖片,轉(zhuǎn)換成流輸出
@RequestMapping(value="showImageDiaLog.do",params={"action=showImageDiaLog"})
public void showImageByType(String filename,HttpServletRequest request,HttpServletResponse response) throws IOException{
InputStream inputStream = null;
OutputStream writer = null;
filename = new String(filename.getBytes("ISO-8859-1"),"UTF-8");
try {
inputStream = new FileInputStream(new File(Constants.getApplicationValue("C\:\\\myeclipseWork\\image\\")+filename));
writer = response.getOutputStream();
byte[] buf = new byte[1024];
int len = 0;
while ((len = inputStream.read(buf)) != -1) {
writer.write(buf, 0, len); //寫
}
} catch (Exception e) {
logger.error(e.toString());
} finally{
if(inputStream != null){
inputStream.close();
}
if(writer != null){
writer.close();
}
}
}
Android代碼
請求地址霸奕,出入請求的文件名
private String url = "http://192.168.1.132:8080/eSAM/showImageDiaLog.do?action=showImageDiaLog&filename=1.jpg";
使用glide框架獲取圖片展示
Glide.with(MainActivity.this)
.load(url)
.into(imageView);
保存在本地吭敢,工具類
package com.example.image;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import java.io.File;
import java.io.FileOutputStream;
/**
* Created by user on 20/9/2017.
*/
public class SDFileHelper {
private Context context;
public SDFileHelper() {
}
public SDFileHelper(Context context) {
super();
this.context = context;
}
//Glide保存圖片
public void savePicture(final String fileName, String url){
Glide.with(context).load(url).asBitmap().toBytes().into(new SimpleTarget<byte[]>() {
@Override
public void onResourceReady(byte[] bytes, GlideAnimation<? super byte[]> glideAnimation) {
try {
savaFileToSD(fileName,bytes);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
//往SD卡寫入文件的方法
public void savaFileToSD(String filename, byte[] bytes) throws Exception {
//如果手機(jī)已插入sd卡,且app具有讀寫sd卡的權(quán)限
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
String filePath = Environment.getExternalStorageDirectory().getCanonicalPath()+"/budejie";
File dir1 = new File(filePath);
if (!dir1.exists()){
dir1.mkdirs();
}
filename = filePath+ "/" + filename;
//這里就不要用openFileOutput了,那個是往手機(jī)內(nèi)存中寫數(shù)據(jù)的
FileOutputStream output = new FileOutputStream(filename);
output.write(bytes);
//將bytes寫入到輸出流中
output.close();
//關(guān)閉輸出流
Toast.makeText(context, "圖片已成功保存到"+filePath, Toast.LENGTH_SHORT).show();
Log.e("filePath:",filePath);
} else {
Toast.makeText(context, "SD卡不存在或者不可讀寫", Toast.LENGTH_SHORT).show();
}
}
}
保存在sd卡
//保存圖片在本地
SDFileHelper helper = new SDFileHelper(MainActivity.this);
helper.savePicture("b.jpg",url);