Android上传图片到服务器

时间:2022-04-06 09:23:04

一.android需要导入异步请求的jar包 AsyncHttpClient 

public static void reg(final Context cont,Bitmap photodata,String regData) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream(); //将bitmap一字节流输出 Bitmap.CompressFormat.PNG 压缩格式,100:压缩率,baos:字节流
photodata.compress(Bitmap.CompressFormat.PNG, 100, baos);
baos.close();
byte[] buffer = baos.toByteArray();//将图片的字节流数据加密成base64字符输出
String photo = Base64.encodeToString(buffer, 0, buffer.length,Base64.DEFAULT); //photo=URLEncoder.encode(photo,"UTF-8");
RequestParams params = new RequestParams();
params.put("photo", photo);
params.put("name", "woshishishi");//传输的字符数据
String url = "http://10.0.2.2:8080/IC_Server/servlet/RegisterServlet1";
AsyncHttpClient client = new AsyncHttpClient();
client.post(url, params, new AsyncHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, String content){
Toast.makeText(cont, "头像上传成功!"+content, 0)
.show();
}
@Override
public void onFailure(Throwable e, String data){
Toast.makeText(cont, "头像上传失败!", 0)
.show();
}
}); } catch (Exception e) {
e.printStackTrace();
} } 二.服务器的代码(用的是springmvc)
@RequestMapping("/post")
public void post(HttpServletResponse response , Post post
//,MultipartFile image
,String image
)throws IOException{
Receipt receipt = new Receipt();
try {
/*// 二进制流 上传图片
if(image!=null && image.getOriginalFilename()!=null && image.getOriginalFilename().length()>0){
//原始名称
String originalFilename = image.getOriginalFilename();
//新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
String saveName = ImageUtil.findFilePathByFileName(newFileName);
System.out.println("O______________________________________K");
//新图片
File newFile = new File(saveName);
if(!newFile.exists()){
newFile.mkdir();
}
//将内存中的数据写入磁盘
image.transferTo(newFile);
System.out.println("O______________________________________");
//将新图片名称写到itemsCustom中
post.setImg(newFileName);
}else {
post.setImg("");
}*/ // ================================= 字符串接收文件
if(image!=null && image.length()>0){ byte[] photoimg = new BASE64Decoder().decodeBuffer(image);
for (int i = 0; i < photoimg.length; ++i) {
if (photoimg[i] < 0) {
// 调整异常数据
photoimg[i] += 256;
}
}
String newFileName = UUID.randomUUID() + ".png";
String saveName = ImageUtil.findFilePathByFileName(newFileName);
File newFile = new File(saveName);
if(!newFile.exists()){
newFile.createNewFile();
}
FileOutputStream out = new FileOutputStream(newFile);
out.write(photoimg);
out.flush();
out.close();
post.setImg(newFileName);
logger.debug("文件接收成功");
}else {
post.setImg("");
}

三.工具类

public static String rootPathString = "WebRoot/WEB-INF/upload";

    public static String findFilePathByFileName(String fileName) {
if(fileName == null || fileName.trim().isEmpty()){
return "/default.png";
}
int hashcode = fileName.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15
String dir = rootPathString + "/" + dir1 + "/" + dir2; //upload\2\3 upload\3\5
File file = new File(dir);
if(!file.exists()){
//创建目录
file.mkdirs();
}
return dir+"/"+fileName;
}

ncHttpClient