文件上传 1. 从路径A复制到路径B 2. 通过流上传文件

  1. 从路径A复制到路径B
/**
	 * 根据文件路径上传文件
	 * @param path
	 * @param fileDocment
	 * @return
	 */
	private String fileUploadByFilePath(String path, String fileDocment) {
		// 读取图片
		File fileImage = new File(path);
		String filepath = fileDocment + File.separator + fileImage.getName();
		
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(fileImage);// 建立一个输入流对象
		} catch (FileNotFoundException e1) {
			log.error("read file error{}", e1);
		}
		
		// 写入路径
		File fileParent = new File(fileDocment);// 新建文件目录
		if (!fileParent.exists()) {// 不存在则创建路径
			fileParent.mkdirs();
		}
		File fileElectronicFence = new File(filepath);
		FileOutputStream fos = null;
		if (!fileElectronicFence.exists()) {
			try {
				fileElectronicFence.createNewFile();
				fos = new FileOutputStream(filepath);
				byte[] buf = new byte[1024];// 每次读入文件数据量
				int len = -1;
				while ((len = (fis.read(buf))) != -1) {
					fos.write(buf);
					fos.flush();
				}
			} catch (IOException e) {
				log.error("create file error{}", e);
			} finally {

				try {
					fos.flush();
					fos.close();
					fis.close();
				} catch (IOException e) {
					log.error("close OutputStream fail{}", e);
				}
			}
		}
		return filepath;
	}

  1. 通过流上传文件
 /** 
     * 描述 : <将文件保存到指定路径>. <br> 
     *<p> 
     * 
     * @param multifile 
     * @param path 目标路径
	 * @param fileName 文件名称
     * @return 
     * @throws IOException 
     */  
    public static String saveFileToServer(MultipartFile multifile, String path, String fileName)  
            throws IOException {  
        // 创建目录  
        File dir = new File(path);  
        if (!dir.exists()) {  
            dir.mkdir();  
        }  
        // 读取文件流并保持在指定路径  
        InputStream inputStream = multifile.getInputStream();  
        OutputStream outputStream = new FileOutputStream(path  
                + fileName);  
        byte[] buffer = multifile.getBytes();  
        int bytesum = 0;  
        int byteread = 0;  
        while ((byteread = inputStream.read(buffer)) != -1) {  
            bytesum += byteread;  
            outputStream.write(buffer, 0, byteread);  
            outputStream.flush();  
        }  
        outputStream.close();  
        inputStream.close();  
  
        return path+ fileName;  
    }  ;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值