APP接口传的base64图片保存到服务器中。(1、保存到服务器本地,2、保存到服务器的共享文件夹中)

在写APP接口的时候,传上来的图片格式是BASE64,(不知道有没有其他的方式),就只能用base64来存取图片。

第一种方式是存取相关的图片到本地文件夹中:

直接用base64的字符串进行存取。

public String uploadPicture(String photo) {
		String path="";
        if( photo!= null && !"".equals(photo)){
            //获取图片上传地址
            Properties properties = new Properties();
            try {
                properties.load(this.getClass().getResourceAsStream("/filepath.properties"));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            String rootPath = getClass().getResource("/").getFile().toString().replaceAll("%20", " ");
            rootPath = rootPath.substring(0, rootPath.indexOf("/WEB-INF"));
            //String path1 = rootPath+properties.getProperty("image2.url");
            //图片上传处理
            Map<String,byte []> photoMap = new HashMap<String,byte []>();
            try {
                photoMap = UploadImageUtil.constructImageData(photo);
                //UploadImageUtil.uploadImage(photoMap,path1);
                //上传图片到制定的文件夹中。配置文件中image.address 的位置  
                  UploadImageUtil.uploadImage(photoMap,properties.getProperty("image.address"));
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            path = UploadImageUtil.getImageNames(photoMap);
        }
        return path;
	}	
类文件的写法:
UploadImageUtil
package com.lingnet.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;


/**
 * 图片上传工具类
 * @ClassName: UploadImageUtil 
 * @author
 * @date 2015-1-9 上午11:58:32 
 */
public class UploadImageUtil {
	
	/**
	 * @Title: uploadImage 
	 * @param map 是key为图片名,value为图片字节数组格式的map
	 * @param destPath  是图片保存在本地硬盤的路徑,如
	 
	 * @throws IOException 
	 * @since 2015-1-9 V 1.0
	 */
	public static void uploadImage(Map<String,byte []> map, String destPath) throws IOException {
		
		String fileName ;//文件名
		
		byte [] buf ;//读写图片数据
		
		FileOutputStream fos = null;
		
		BufferedOutputStream bos = null;
		
		//循环读取文件并上传
		for ( Entry<String, byte[]> entry : map.entrySet() ){
			
			fileName = entry.getKey();
			
			buf = entry.getValue();
	
			File destDir = new File(destPath);
	
			if (!destDir.exists())
				destDir.mkdirs();
	
			// 保存图片到指定路径
			File file = new File(destDir, fileName);
			fos = new FileOutputStream(file);
	
			bos = new BufferedOutputStream(fos);
			bos.write(buf);
		    
            //bos.flush();
    
            bos.close();
			 
	         /*   Image src = ImageIO.read(file);
	            int wideth = src.getWidth(null);
	            int height = src.getHeight(null);
	            BufferedImage image = new BufferedImage(wideth, height,
	                    BufferedImage.TYPE_INT_RGB);
	            Graphics g = image.createGraphics();
	            g.drawImage(src, 0, 0, wideth, height, null);
			 //水印文件
            File _filebiao = new File("D:img.png");
            Image src_biao = ImageIO.read(_filebiao);
            int wideth_biao = src_biao.getWidth(null);
            int height_biao = src_biao.getHeight(null);
            g.drawImage(src_biao, (wideth - wideth_biao)+5,
                    (height - height_biao)+5, wideth_biao, height_biao, null);
            //水印文件结束
            g.dispose();
			
            FileOutputStream out = new FileOutputStream(file);
            
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            encoder.encode(image);
            out.close();*/
		}

	}

	/**
	 * 将用户提交上来的图片信息构造成可以存入数据库和本地硬盘的有效信息
	 * @Title: constructImageData 
	 * @param pictures
	 * @return key为图片名,value为经过Base64Decoder处理的图片字节数组格式的map
	 * @throws IOException 
	 * String[] 
	 * @since 2015-1-9 V 1.0
	 */
	public static Map<String,byte []> constructImageData(String pictures) throws IOException {

		//List<Map<String,byte []>> list_picture = new ArrayList<Map<String,byte []>>();
		Map<String,byte []> map_picture = new HashMap<String,byte []>();
		//先解析上传的图片pictures
		String [] images = pictures.split(",");
		for (int i = 0 ; i <images.length;i++){
			if(images[i]!=null&&!"".equals(images[i])&&!"null".equals(images[i])){

			    String image = images[i];
				//map_picture = new HashMap<String,byte []>();
				//构造key为图片名,value为图片字节数组格式的map
			    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
			    String dateStr = sdf.format(new Date());
			    Random random = new Random();
			    dateStr +=random.nextInt(4);
				map_picture.put("imag"+dateStr+".jpg",
						Base64Util.transferImageStringToByteArray(image));
				
				//放入集合
				//list_picture.add(map_picture);
			
			}
		}
		return map_picture;
		
	}
	
	/**
	 * 获取所有图片的名称
	 * @Title: getImageNames 
	 * @param map
	 * @return String 
	 * @since 2015-1-9 V 1.0
	 */
	public static String getImageNames(Map<String,byte []> map){
		String names = "";
		for ( String str : map.keySet() ) {
			names += "".equals(names)?str:","+str;
		}
		return names;
	}
	
	/**
	 * 删除图片
	 * @Title: deleteFile 
	 * @param wholeFilePath 
	 * void 
	 * @author 李志新
	 * @since 2015-1-12 V 1.0
	 */
	public static Boolean deleteFile(String wholeFilePath){
		File file = new File (wholeFilePath);
		if (file.exists()){
			file.delete();
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 复制图片
	 * @Title: copy 
	 * @param fileFrom
	 * @param fileTo
	 * @throws IOException 
	 * void 
	 * @since 2015-2-2 V 1.0
	 */
	public static void copy(String fileFrom, String fileTo) throws IOException{
		
		FileInputStream fis = new FileInputStream(fileFrom);
		
		BufferedInputStream bis = new BufferedInputStream(fis);
		
		FileOutputStream fos = new FileOutputStream(fileTo);
		
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		
		int d = -1;
		
		while ((d = bis.read()) != -1){
			
			bos.write(d);
		}
		
		bos.close();
		
		bis.close();
		
	}

}

配置文件的写法:

    filepath.properties:

image.address=E\:/picture

这种方法比较简单,可以存到制定的文件夹中,读取方法可以参考之前写的文章用来读取。


第二种、因为是客户需求,要把文件和图片等存到相关的服务器共享文件夹中,所以需要用到SMB来处理

public static String imgUpload2(Object image,String path)throws Exception{
    	path = getPropert("filepath.properties", "image.address");
    	String img = "";
    	if(image!=null&&!"".equals(image)){
			img = image.toString();
		}
    	if (!path.startsWith("smb")) {
    		Map<String, byte[]> picMap = UploadImageUtil
    				.constructImageData(img);
    		// 保存图片
    		UploadImageUtil.uploadImage(picMap, path);
//    		String imgs[] = UploadImageUtil.getImageNames(picMap).split(",");
    		path = UploadImageUtil.getImageNames(picMap);
    		return path;
		}else{
			//将base图片转成可以直接存储的信息
			Map<String, byte[]> picMap = UploadImageUtil
    				.constructImageData(img);
			//base64转成MultipartFile 进行操作
			//MultipartFile imageMultipart = base64ToMultipart(image.toString());
			String res = uploadPic(picMap);
			return res;
		}
    }

其中uploadPicd的方法中写了SMB的用法:

  

public static String uploadPic(Map<String, byte[]> files) {
		InputStream in = null;
		OutputStream out = null;
		String trueFileName = "";
		try {
			String path = getPropert("filepath.properties", "image.address");// 远程服务器共享文件夹名称
			//String fileName = file.getOriginalFilename();
			for ( Entry<String, byte[]> entry : files.entrySet() ){
				
				String fileName = entry.getKey();
				InputStream sbs = new ByteArrayInputStream(files.get(fileName)); 
				trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
				SmbFile remoteFile = new SmbFile(path  + trueFileName);
				remoteFile.connect();
				in = new BufferedInputStream(sbs);
				out = new BufferedOutputStream(new SmbFileOutputStream(remoteFile));
				byte []buffer = new byte[1024];  
	            while((in.read(buffer)) != -1){  
	                out.write(buffer);  
	                buffer = new byte[1024];  
	            } 
				
		   }
			
		} catch (Exception e) {
			String msg = "发生错误:" + e.getLocalizedMessage();
			System.out.println(msg);
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (Exception e) {
			}
		}
		return trueFileName;
	}

这样就吧图片存到共享文件夹中了。

备注:SMB地址的写法  :  smb://{username}:{pwd}@{ip}/{文件夹名称}

                             举例:   smb://administrator:123456@172.16.10.136/smb

jar 包: jcifs-1.3.15.jar(网上有很多)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值