当前位置: 首页 > 工具软件 > CR4Decoder > 使用案例 >

使用base64decoder对文件互转来提供文件上传接口

景哲
2023-12-01
淘宝里面的html用base64转换图片,不知道为什么,不过看起来好像很美好,给个地址让大家玩玩,谁要有更全面的介绍也留下言

http://www.rssria.com/blogx/wp-content/uploads/2010/05/imgbase64/UML.html



Java代码

代码
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Base64Image {
public static void main(String[] args) {
// 测试从Base64编码转换为图片文件
String strImg = "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGBQgHBwcJCQgKDBQNDAsLDBkSEw8UHRofHh0aHBwgJC4nICIsIxwcKDcpLDAxNDQ0Hyc5PTgyPC4zNDL/2wBDAQkJCQwLDBgNDRgyIRwhMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjL/wAARCADcALIDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJm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3dACeXH/AM9KKTaKKAP/2Xd3d2lkNWNuTWV4OGFGcEFwcEYrZGl2VkcwUk5LQT09";
GenerateImage(strImg, "D:\\wangyc.jpg");

// 测试从图片文件转换为Base64编码
System.out.println(GetImageStr("d:\\wangyc.jpg"));
}

public static String GetImageStr(String imgFilePath) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
byte[] data = null;

// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgFilePath);
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}

// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);// 返回Base64编码过的字节数组字符串
}

public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}


采纳:http://www.cnblogs.com/mofish/archive/2010/11/26/1889126.html


// 下面是自己提供的图片上传接口 对于图片的上传可以用java自带的流上传 我这是因为直接从写的项目中拷下 没来得及去修改

	/**
* 上传图片
* @param request
* @param response
* @return
* @throws UnsupportedEncodingException
*/
@SuppressWarnings("unused")
@RequestMapping(value="/img/uploadAuthImg",method={RequestMethod.GET,RequestMethod.POST})
public String uploadAuth(@PathVariable int uid,HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException{
response.setContentType("text/plain;charset=utf-8");
request.setCharacterEncoding("UTF-8");
if (logger.isInfoEnabled()) {
logger.info("--UploadImgController.uploadAuth--->start");
}
JSONObject json = new JSONObject();
Map<String, String> param = this.paramToMap(request);
if (logger.isDebugEnabled()) {
logger.debug("--UploadImgController.uploadAuth-parameter->" + param);
}
try{
// 处理业务逻辑后再掉统一用户中心
String brandList = this.uploadAuthImg(param); // 业务逻辑处理
logger.info("业务逻辑返回参数:"+brandList);
//解析上传的参数
JSONObject jo = JSONObject.fromObject(brandList);
if(StringUtils.isEmpty(brandList)){
json.put(ResultKeyConstant.DATA, "");
json.put(ResultKeyConstant.ERROR_CODE, ErrorCodeConstant.COMMON_UNKNOWN_ERROR); // 系统内部错误
json.put(ResultKeyConstant.ERROR_MESSAGE, "上传图片错误");
}else if(jo.get("state")!=null&&jo.get("state").toString().equals("1")){
json.put(ResultKeyConstant.DATA, brandList);
json.put(ResultKeyConstant.ERROR_CODE, ErrorCodeConstant.COMMON_UNKNOWN_ERROR); // 系统内部错误
json.put(ResultKeyConstant.ERROR_MESSAGE, jo.get("msg"));
}
else{
//访问统一用户中心 提供认证信息
Map<String,Object> memberMap = new HashMap<String,Object>();
memberMap.put("user_name",this.getParamValue(param.get("param"), "user_name"));
memberMap.put("member_id",this.getParamValue(param.get("param"), "mid"));
String fullPath = jo.get("fullPath")==null?"":jo.get("fullPath").toString();
memberMap.put("identify_img",fullPath);
memberMap.put("identify",this.getParamValue(param.get("param"), "identify"));
memberMap.put("biz_key",3);
logger.info("解析成功后得到的参数:"+"param_json="+JSONObject.fromObject(memberMap).toString());
}


}catch(Exception e){
logger.error(e);
json.put(ResultKeyConstant.DATA, "");
json.put(ResultKeyConstant.ERROR_CODE, ErrorCodeConstant.COMMON_UNKNOWN_ERROR);// 系统内部错误
json.put(ResultKeyConstant.ERROR_MESSAGE, messageService.getMessage(ErrorCodeConstant.COMMON_UNKNOWN_ERROR));

}
return null;
}


public Map<String, String> paramToMap(HttpServletRequest request) {
HashMap<String, String> map = new HashMap<String, String>();
Map<String, String[]> m = request.getParameterMap();
for (Entry<String, String[]> entry : m.entrySet()) {
map.put(entry.getKey().toString(), entry.getValue()[0]);
}
return map;
}



public String uploadAuthImg(Map<String, String> patam){
Map<Object, Object> lmap = new HashMap<Object, Object>();
String result = null;
try {
if (logger.isInfoEnabled()) {
logger.info("--AreaServiceV100Impl.uploadAuthImg---parameter->" + patam);
}
String param = patam.get("param");
if(StringUtil.hasText(param)){
JSONObject json = JSONObject.fromObject(param);
String name = json.get("imgName") == null ? "" : StringUtil.trim(json.get("imgName"));
String mid = json.get("mid") == null ? "" : StringUtil.trim(json.get("mid"));
String imgData = json.get("imgData") == null ? null : json.get("imgData").toString();/// 图片数据
byte[] imgbuffer = new BASE64Decoder().decodeBuffer(imgData); // 对android传过来的图片字符串进行解码
if (name == null || "".equals(name)) {
lmap.put("state", "1");
lmap.put("msg", "图片名称为空!");
return JSONObject.fromObject(lmap, ControllerUtils.convertJsonConfigDate("yyyy-MM-dd HH:mm:ss")).toString();
}
// 拼接上传路径
String extName = "";// 原图片的名称(如:12 不要后面的后缀名)
if (name.lastIndexOf(".") >= 0) {
extName = name.substring(name.lastIndexOf(".") + 1);
}
InputStream sbs = new ByteArrayInputStream(imgbuffer);
String domain = "http://127.0.0.1"; //自定义图片服务器
String masterFileId = null;
try {
masterFileId = fastDFSStorageManager.uploadResource(extName, IOUtils.toByteArray(sbs), null); //使用fastdfs-1.2-jar.jar这个jar包
} catch (Exception e) {
logger.error("上传原始图片失败!");
lmap.put("state", "1");// 上传失败
lmap.put("msg", "对不起,上传图片失败!");
return null;
}
lmap.put("fullPath", domain + masterFileId);// 访问全路径
lmap.put("state", "0");// 上传成功
lmap.put("msg", "上传图片成功!");
lmap.put("img", masterFileId);
}
else {
// 图片类型错误
lmap.put("state", "1");
lmap.put("msg", "对不起,您上传的图片类型错误!");
}
result = JSONObject.fromObject(lmap, ControllerUtils.convertJsonConfigDate("yyyy-MM-dd HH:mm:ss")).toString();
if (logger.isInfoEnabled()) {
logger.info("--AreaServiceV100Impl.getAreasByLevel---result-->" + result);
}
}catch(Exception e){
logger.error(e);
}
return result;
}



//接口 使用的fastdfs的jar包
package com.mes.fastdfs;

import java.util.Map;

/**
* 文件存储管理工具
* @author Administrator
*
*/
public interface FastDFSStorageManager {
/**
* 上传文件
* @param extension 扩展名
* @param resourceData 二进制数据
* @param mataData 元数据
* @return
* @throws Exception
*/
String uploadResource(final String extension, final byte[] resourceData, final Map<String, String> mataData) throws Exception ;

/**
* 上传从文件
* @param masterFileId 主文件ID
* @param prefixName 后缀名
* @param extension 文件扩展名
* @param resourceData 二进制数据
* @param mataData 元数据
* @return
* @throws Exception
*/
String uploadResourceBySlave(final String masterFileId, final String prefixName, final String extension, final byte[] resourceData, final Map<String, String> mataData) throws Exception;


/**
* 根据上传路径设置元数据
* @param path 路径
* @param mataData 元数据
* @param isOverwrite 是否覆盖原有数据
* @return
* @throws Exception
*/
boolean setResourceMataDataByPath(final String path, final Map<String, String> mataData, boolean isOverwrite) throws Exception ;

/**
* 获取元数据信息
* @param path fastdfs路径
* @return
* @throws Exception
*/
Map<String, String> queryMetaDataByPath(final String path) throws Exception ;

/**
* 删除
* @param path
* @throws Exception
*/
boolean deleteResourceByPath(final String path) throws Exception ;


/**
* 下载
* @param path 文件ID
* @return
* @throws Exception
*/
byte[] downloadByPath(final String path) throws Exception ;
}


//接口的实现类
package com.mes.fastdfs;

import java.util.HashMap;
import java.util.Map;

import org.csource.common.NameValuePair;
import org.csource.fastdfs.ProtoCommon;
import org.csource.fastdfs.StorageClient1;
import org.csource.fastdfs.StorageServer;
import org.csource.fastdfs.TrackerClient;
import org.csource.fastdfs.TrackerServer;

/**
* fastDFS管理工具
*
* @author Administrator
*
*/
public class FastDFSStorageManagerImpl implements FastDFSStorageManager {

private StorageClientTemplate storageClientTemplate;

@Override
public String uploadResource(final String extension, final byte[] resourceData, final Map<String, String> mataData) throws Exception {
return storageClientTemplate.execute(new AbstractStorageClientReturnedCallback<String>() {

@Override
public String doInStorageClient(TrackerClient trackerClient, TrackerServer trackerServer, StorageServer storageServer) throws Exception {
StorageClient1 storageClinet = new StorageClient1(trackerServer, storageServer);

NameValuePair[] nameValuePairs = null;
if ((mataData != null) && (mataData.size() > 0)) {
nameValuePairs = new NameValuePair[mataData.size()];
int i = 0;
for (Map.Entry<String, String> entry : mataData.entrySet()) {
nameValuePairs[i++] = new NameValuePair(entry.getKey(), entry.getValue());
}
}

return storageClinet.upload_file1(resourceData, extension, nameValuePairs);
}

});
}

@Override
public Map<String, String> queryMetaDataByPath(final String path) throws Exception {
return storageClientTemplate.execute(new AbstractStorageClientReturnedCallback<Map<String, String>>() {

@Override
public Map<String, String> doInStorageClient(TrackerClient trackerClient, TrackerServer trackerServer, StorageServer storageServer) throws Exception {
StorageClient1 storageClinet = new StorageClient1(trackerServer, storageServer);
NameValuePair[] nameValuePairs = storageClinet.get_metadata1(path);

Map<String, String> metaData = new HashMap<String, String>();
if ((nameValuePairs != null) && (nameValuePairs.length > 0)) {
for (NameValuePair entry : nameValuePairs) {
metaData.put(entry.getName(), entry.getValue());
}
}
return metaData;
}

});
}

@Override
public boolean deleteResourceByPath(final String path) throws Exception {
return storageClientTemplate.execute(new AbstractStorageClientReturnedCallback<Boolean>(){

@Override
public Boolean doInStorageClient(TrackerClient trackerClient, TrackerServer trackerServer, StorageServer storageServer) throws Exception {
StorageClient1 storageClinet = new StorageClient1(trackerServer, storageServer);
return storageClinet.delete_file1(path) == 0;
}

}) ;
}

public StorageClientTemplate getStorageClientTemplate() {
return storageClientTemplate;
}

public void setStorageClientTemplate(StorageClientTemplate storageClientTemplate) {
this.storageClientTemplate = storageClientTemplate;
}

/* (non-Javadoc)
* @see com.mes.fastdfs.FastDFSStorageManager#uploadResourceBySlave(java.lang.String, java.lang.String, byte[], java.util.Map)
*/
@Override
public String uploadResourceBySlave(final String masterFileId, final String prefixName, final String extension, final byte[] resourceData, final Map<String, String> mataData) throws Exception {
return storageClientTemplate.execute(new AbstractStorageClientReturnedCallback<String>() {

@Override
public String doInStorageClient(TrackerClient trackerClient, TrackerServer trackerServer, StorageServer storageServer) throws Exception {
StorageClient1 storageClinet = new StorageClient1(trackerServer, storageServer);

NameValuePair[] nameValuePairs = null;
if ((mataData != null) && (mataData.size() > 0)) {
nameValuePairs = new NameValuePair[mataData.size()];
int i = 0;
for (Map.Entry<String, String> entry : mataData.entrySet()) {
nameValuePairs[i++] = new NameValuePair(entry.getKey(), entry.getValue());
}
}

return storageClinet.upload_file1(masterFileId, prefixName, resourceData, extension, nameValuePairs) ;
}

});
}

@Override
public boolean setResourceMataDataByPath(final String path, final Map<String, String> mataData, final boolean isOverwrite) throws Exception {
return storageClientTemplate.execute(new AbstractStorageClientReturnedCallback<Boolean>() {

@Override
public Boolean doInStorageClient(TrackerClient trackerClient, TrackerServer trackerServer, StorageServer storageServer) throws Exception {
StorageClient1 storageClinet = new StorageClient1(trackerServer, storageServer);

NameValuePair[] nameValuePairs = null;
if ((mataData != null) && (mataData.size() > 0)) {
nameValuePairs = new NameValuePair[mataData.size()];
int i = 0;
for (Map.Entry<String, String> entry : mataData.entrySet()) {
nameValuePairs[i++] = new NameValuePair(entry.getKey(), entry.getValue());
}
}
return storageClinet.set_metadata1(path, nameValuePairs, isOverwrite ? ProtoCommon.STORAGE_SET_METADATA_FLAG_OVERWRITE: ProtoCommon.STORAGE_SET_METADATA_FLAG_MERGE) == 0;
}

});
}

@Override
public byte[] downloadByPath(final String path) throws Exception {
return storageClientTemplate.execute(new AbstractStorageClientReturnedByteCallback(){

@Override
public byte[] doInStorageClient(TrackerClient trackerClient, TrackerServer trackerServer, StorageServer storageServer) throws Exception {
StorageClient1 storageClinet = new StorageClient1(trackerServer, storageServer);
return storageClinet.download_file1(path);
}

}) ;
}



}
 类似资料: