MD5加密文件后,上传文件

来源:互联网 发布:天津婚纱摄影 知乎 编辑:程序博客网 时间:2024/05/16 08:54

   由于会重复上传相同的图片,所以进行了MD5加密,但是发现文件流被加密后,上传后没有图片,百度一下才知道,inputstream是个单向流,操作一次后,就被清空,没办法只能做两次连接,下面是代码:

 md5加密文件

import java.io.BufferedInputStream;import java.io.ByteArrayOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.nio.MappedByteBuffer;import java.nio.channels.FileChannel;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException;import org.apache.log4j.Logger;import org.springframework.web.multipart.MultipartFile;public class MD5FileUtil {private static Logger logger = Logger.getLogger(MD5FileUtil.class);protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6','7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };public static MessageDigest messagedigest = null;static {try {messagedigest = MessageDigest.getInstance("MD5");} catch (NoSuchAlgorithmException e) {logger.error("MD5FileUtil messagedigest", e);}}public static void readInputStream(InputStream inStream,String param) throws Exception{   FileOutputStream fos = new FileOutputStream("D:/"+param);;          //创建一个Buffer字符串          byte[] buffer = new byte[1024];          //每次读取的字符串长度,如果为-1,代表全部读取完毕          int len = 0;                 //使用一个输入流从buffer里把数据读取出来          while( (len=inStream.read(buffer)) != -1 ){              //用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度          fos.write(buffer, 0, len);        fos.flush();        }          //关闭输入流             fos.close();          }  public static String getFileMD5String(File file) throws IOException {FileInputStream in = new FileInputStream(file);FileChannel ch = in.getChannel();MappedByteBuffer byteBuffer = ch.map(FileChannel.MapMode.READ_ONLY, 0,file.length());messagedigest.update(byteBuffer);ch.close();in.close();return bufferToHex(messagedigest.digest());}public static String getFileMD5String(InputStream is) throws IOException{byte[] buffer = new byte[1024];int read = 0;while((read = is.read(buffer))>0){messagedigest.update(buffer,0,read);}return bufferToHex(messagedigest.digest());}private static String bufferToHex(byte bytes[], int m, int n) {StringBuffer stringbuffer = new StringBuffer(2 * n);int k = m + n;for (int l = m; l < k; l++) {appendHexPair(bytes[l], stringbuffer);}return stringbuffer.toString();}private static String bufferToHex(byte bytes[]) {return bufferToHex(bytes, 0, bytes.length);}private static void appendHexPair(byte bt, StringBuffer stringbuffer) {char c0 = hexDigits[(bt & 0xf0) >> 4];char c1 = hexDigits[bt & 0xf];stringbuffer.append(c0);stringbuffer.append(c1);}public static void main(String[] args) throws IOException {//  new一个URL对象          URL url = new URL("http://i.gtimg.cn/qqlive/img/jpgcache/files/qqvideo/h/hegjvmzm4locorl_l.jpg");          URL url1=new URL("http://i.gtimg.cn/qqlive/img/jpgcache/files/qqvideo/h/hegjvmzm4locorl_l.jpg");        //打开链接          HttpURLConnection conn = (HttpURLConnection)url.openConnection();         HttpURLConnection conn1 = (HttpURLConnection)url1.openConnection();        //设置请求方式为"GET"          conn.setRequestMethod("GET");         conn1.setRequestMethod("GET");         //超时响应时间为5秒          conn.setConnectTimeout(5 * 1000);        conn1.setConnectTimeout(5 * 1000);         //通过输入流获取图片数据          InputStream inStream = conn.getInputStream();        InputStream inStream1 = conn1.getInputStream(); String result=getFileMD5String(inStream);try {//readInputStream(inStream1, result+".png");SaveFileInputStream.saveFileFromInputStream(inStream1,"D://", result+".png");} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}        }}
将文件写入制定文件夹

import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;/** * 上传图片到工程中 * @remark * @author  * @createTime  */public class SaveFileInputStream {public static  void saveFileFromInputStream(InputStream stream,String path,String picPath) throws IOException{FileOutputStream fs=new FileOutputStream( path + "/"+ picPath);byte[] buffer =new byte[1024*1024];int byteread = 0; while ((byteread=stream.read(buffer))!=-1){fs.write(buffer,0,byteread);fs.flush();}fs.close();stream.close();}       }


0 0