1、对一个文件babse64加密,再上传到指定位置。使用多线程可以提高文件上传速度。2、java 实现:@Slf4jpublic class FileUploadDemo {public static void uploadFiles(String localFilePath,String uploadFile){InputStream is = null;FileOutputStream os = null;//获取上传文件的base64编码文件并进行解码try {is = new ByteArrayInputStream(new BASE64Decoder().decodeBuffer(localFilePath));//创建一个文件输出流os = new FileOutputStream(new File(uploadFile));//创建一个缓冲区byte[] buffer = new byte[10 * 1024 * 1024];//判断输入流中的数据是否已经读完的标识//循环将输入流读入到缓冲区当中,(len = in.read(buffer)>0表示里面还有数据)int length;while ((length = is.read(buffer))>0){os.write(buffer,0,length);}os.flush();} catch (FileNotFoundException e) {log.error("未找到上传的文件"+ e);e.printStackTrace();// throw new ServerException("未找到文件");}catch (IOException e){log.error("文件读取异常" + e);e.printStackTrace();}finally {if(is!=null){try {is.close();} catch (IOException e) {log.error("Exception:" + e);e.printStackTrace();}}if(os!=null){try {os.close();} catch (IOException e) {e.printStackTrace();log.error("Exception:"+ e);}}}}public static String EncoderFile(String filePath){InputStream is = null;byte[] data = null;try {//读取文件所有字节,方法1// is = new FileInputStream(filePath);// data = new byte[is.available()];// is.read(data);// is.close();//读取文件所有字节,方法2data = Files.readAllBytes(Paths.get(filePath));}catch (FileNotFoundException e) {log.error("未找到上传的文件"+ e);e.printStackTrace();// throw new ServerException("未找到文件");} catch (IOException e) {e.printStackTrace();}finally {if(is!=null){try {is.close();} catch (IOException e) {log.error("Exception:" + e);e.printStackTrace();}}}BASE64Encoder encoder = new BASE64Encoder();return encoder.encode(data);}//创建线程池static ThreadPoolExecutor executor = new ThreadPoolExecutor(2,50,10, TimeUnit.SECONDS,new LinkedBlockingQueue<>(100), Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());public static void main(String[] args) {//计算文件上传时间StopWatch stopWatch = new StopWatch();stopWatch.start();String localPath = "/Users/yangxusheng/Desktop/2.pdf";String s = EncoderFile(localPath);String s1 = EncoderFile(localPath);String s2 = EncoderFile(localPath);String uploadPath = "/Users/ttt/Desktop/1.pdf";String uploadPath1 = "/Users/ttt/Desktop/1.pdf";String uploadPath2 = "/Users/ttt/Desktop/1.pdf";//一般情况// uploadFiles(s,uploadPath);// uploadFiles(s1,uploadPath1);// uploadFiles(s2,uploadPath2);//使用多线程的情况CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(()->{uploadFiles(s,uploadPath);return 200;},executor);CompletableFuture<Integer> future2 = CompletableFuture.supplyAsync(()->{uploadFiles(s1,uploadPath1);return 300;},executor);CompletableFuture<Integer> future3 = CompletableFuture.supplyAsync(()->{uploadFiles(s2,uploadPath2);return 300;},executor);//stopWatch.stop();System.out.println(stopWatch.getTotalTimeMillis());}}
100字范文,内容丰富有趣,生活中的好帮手!