您的位置:首页 > 移动开发

app接口上传图片(通过转码为Base64格式字符串上传)

2018-03-09 17:59 519 查看
app开发中接口有时会涉及到图片上传,代码如下
接受参数 //上传
String imgName = this.getRequestBase64Img("headImg");
方法 /**
* 上传图片(前台为Base64格式)
* @param fileName 上传图片的属性名
* @return
* @throws Exception
*/
public String getRequestBase64Img(String fileName) throws Exception{
return getRequestBase64File(fileName, Constant.SJYS_IMG);//ROOT_PATH + "/SJYS_IMG/"
}
具体方法 /**
* 上传文件(前台为Base64格式)
* @param fileName 上传文件的名字(前台的属性名称)
* @param filePath 文件保存的目标路径
* @return
* @throws Exception
*/
public String getRequestBase64File(String fileName, String filePath) throws Exception{
//得到前台传递过来的Base64格式的字符串
String fileStr = this.getRequest().getParamValue(fileName);
if (fileStr == null){
return null;
}

if(filePath == null || "".equals(filePath)){
filePath = Constant.XLS_TEMP;//ROOT_PATH + "/uploadTemplates/";
}

//前台生成base64时,是以 ABCDEFWWFE.jpg 这种格式传过来的 .jpg是文件的后缀名
String suffix = fileStr.substring(fileStr.lastIndexOf(".")); //后缀名
fileStr = fileStr.substring(0,fileStr.lastIndexOf(".")); //文件的真正base64内容

//产生的文件名称
String name = getRandomFileName()+suffix;

BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] b = decoder.decodeBuffer(fileStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
// 生成文件
OutputStream out = new FileOutputStream(filePath+name);
out.write(b);
out.flush();
out.close();
return name;
} catch (Exception e) {
return null;
}
}
/**
* 生成随机名字
*/
public String getRandomFileName() {
Random r = new Random();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmssSSS");
StringBuffer sb = new StringBuffer();
sb.append(r.nextInt(100));
sb.append(r.nextInt(100));
sb.append("_");
sb.append(sdf.format(new Date()));
sb.append("_");
sb.append(r.nextInt(100));
sb.append(r.nextInt(100));
return sb.toString();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐