Java-获取文件的方法

Java中获取文件路径的方法

1. 常规方法

public static void getPath() {
		//方式一
		System.out.println(System.getProperty("user.dir"));
		//方式二
		File directory = new File("");
		try {
			//获取标准路径
			System.out.println(directory.getCanonicalPath());
			//获取绝对路径
			System.out.println(directory.getAbsolutePath());
		} catch (Exception e) {
			e.printStackTrace();
		}
		//方式三
		System.out.println(Test.class.getResource("/"));
		System.out.println(Test.class.getResource(""));
		//方式4
		System.out.println(Test.class.getClassLoader().getResource(""));
		System.out.println(Test.class.getClassLoader().getResource("temp.txt"));
	}

	public static void main(String[] args) {
		Test.getPath();
	}

2. Resource获取

//根据传入的地址获取到文件
Resource resource = new ClassPathResource(fileName);
System.out.println("getFile:"+resource.getFile());
System.out.println("getURL:"+resource.getURL());
System.out.println("getDescription:"+resource.getDescription());
System.out.println("getFilename:"+resource.getFilename());
System.out.println("getURI:"+resource.getURI());

总结就是以下几种方式获取文件路径(持续更新)

  1. 通过系统方法获取当前的文件路径

System.getProperty(“user.dir”)

  1. 通过类的全限定类名获取当前类所在的路径

Test.class.getResource("/")
Test.class.getResource("")

  1. 通过类加载器ClassLoader进行获取

Test.class.getClassLoader().getResource("")
Test.class.getClassLoader().getResource(“fileName”)

  1. 通过创建空文件进行获取当前路径
	File  directory = new File("");
	//获取标准路径
	System.out.println(directory.getCanonicalPath());
	//获取绝对路径
	System.out.println(directory.getAbsolutePath());

SpringBoot+Java实现文件上传

使用servlet进行实现文件上传

1、开始

1、pom文件

在pom文件中导入所需的包

<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--文件上传所需-->
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

2、配置文件

spring:
  servlet:
    multipart:
      max-file-size: 300MB
      max-request-size: 500MB
# 文件存储路径,可以自定义
file:
  uploadFolder: D:/mimi/upload
  returnPath: /iti

3、开发接口

开发上传文件的接口

  • Controller层
package com.zukxu.resourcejava.controller.tools;

import com.zukxu.resourcejava.service.IUploadService;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Description: 视频上传接口
 *
 * @author zukxu
 * @date 2020-9-26 15:07:51
 */
@RestController
@RequestMapping("upload")
@AllArgsConstructor
@Api(tags = "文件上传控制层")
public class FileUploadController {

	@Autowired
	private IUploadService uploadService;

	/**
	 * 视频文件上传
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/video")
	public Map<String, Object> uploadVideo(MultipartFile file, HttpServletRequest request) throws Exception {
		return uploadService.uploadVideo(file, request);
	}

	/**
	 * 图片文件上传
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@PostMapping(value = "/image")
	public Map<String, Object> uploadImage(MultipartFile image, HttpServletRequest request) throws Exception {
		return uploadService.uploadImage(image, request);
	}
}

  • service接口层
package com.zukxu.resourcejava.service;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * <p>
 * 视频文件上传服务类
 * </p>
 *
 * @author zukxu
 * @date 2020-9-27 15:17:03
 */
public interface IUploadService {
	/**
	 * 视频文件上传
	 *
	 * @param request
	 * @return
	 */
	public Map<String, Object> uploadVideo(MultipartFile file, HttpServletRequest request) throws Exception;

	/**
	 * 图片文件上传
	 *
	 * @param request
	 * @return
	 */
	public Map<String, Object> uploadImage(MultipartFile file, HttpServletRequest request) throws Exception;
}

  • Service实现类
package com.zukxu.resourcejava.service.impl;

import com.zukxu.resourcejava.service.IUploadService;
import com.zukxu.resourcejava.utils.FrameGrabberKit;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Transactional
@Service("UploadService")
public class UploadServiceImpl implements IUploadService {
	@Value("${file.uploadFolder}")
	private String uploadFolder;

	@Value("${file.returnPath}")
	private String returnPath;

	/**
	 * 视频文件上传
	 */
	@Override
	public Map<String, Object> uploadVideo(MultipartFile file, HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Long time = new Date().getTime();

		String fileName = file.getOriginalFilename();//文件原始名称
		//从最后一个.开始截取。截取fileName的后缀名
		String extName = getExtFie(fileName);	

		String newFileName = time + extName; //文件新名称

		//上传视频存放位置
		String savePath = uploadFolder + "/video/";
		//视频地址
		String filePath = savePath + newFileName;
		File newFile = new File(filePath);
		//判断目标文件所在目录是否存在
		if (!newFile.getParentFile().exists()) {
			//如果目标文件所在的目录不存在,则创建父目录
			newFile.getParentFile().mkdirs();
		}
		//将内存中的数据写入磁盘
		file.transferTo(newFile);
		//视频映射url
		String videoUrl = returnPath+"/video/"+ newFileName;

		//视频封面图处理
		String newImgName = time + ".jpg";
		String frameFile = savePath + newImgName;
		String imgUrlSave = returnPath+"/video/" + newImgName;//图片最终位置路径
		//视频截取封面图
		String imgUrl = FrameGrabberKit.getVedioImg(filePath, frameFile, imgUrlSave);

		resultMap.put("videoUrl", videoUrl);
		resultMap.put("imgUrl", imgUrl);
		return resultMap;
	}

	/**
	 * 图片文件上传
	 */
	@Override
	public Map<String, Object> uploadImage(MultipartFile file, HttpServletRequest request) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Long time = new Date().getTime();

		String fileName = file.getOriginalFilename();//文件原始名称
		String extName = getExtFie(fileName);
		String newFileName = time + extName; //文件新名称
		//设置文件存储路径,可以存放在你想要指定的路径里面
		String savePath = uploadFolder + "/images/"; //上传图片存放位置

		String filePath = savePath + newFileName;
		File newFile = new File(filePath);
		//判断目标文件所在目录是否存在
		if (!newFile.getParentFile().exists()) {
			//如果目标文件所在的目录不存在,则创建父目录
			newFile.getParentFile().mkdirs();
		}

		//将内存中的数据写入磁盘
		file.transferTo(newFile);
		//图片上传保存url
		String imgUrl = returnPath+"/images/" + newFileName;

		resultMap.put("imgUrl", imgUrl);
		return resultMap;
	}
	
	public String getExtFie(String fileName) {
		String extName = "";
		if (null != fileName && fileName.length() > 0) {
			int t = fileName.lastIndexOf(".");
			if (t > 0) {
				extName = fileName.substring(t).toLowerCase();
			}
		}
		return extName;
	}
}
  • 上传配置类WebMvcConfig
package com.zukxu.resourcejava.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

/**
 * Description:
 *
 * @author zukxu
 * @date 2020/9/27 0027 15:27
 */
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
	@Value("${file.uploadFolder}")
	private String uploadFolder;

	@Value("${file.returnPath}")
	private String returnPath;

	/**
	 * 添加静态资源映射路径,css、js等都放在classpath下的static中
	 */
	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		/**
		 * addResourceHandler 指的是对外暴露的访问路径
		 * addResourceLocations 指的是文件配置的目录
		 */

		//文件上传路径映射
			//文件上传路径映射
		registry.addResourceHandler(returnPath + "/video/**")
				.addResourceLocations("file:" + uploadFolder + "/video/");
		registry.addResourceHandler(returnPath + "/images/**")
				.addResourceLocations("file:" + uploadFolder + "/images/");
	}
}


  • 前端页面
    使用antdesign vue进行编写
<template>
  <div class="clearfix">
    <a-upload
      action="http://localhost:8099/upload/image"
      list-type="picture-card"
      :file-list="fileList"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < 8">
        <plus-outlined/>
        <div class="ant-upload-text">Upload</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage"/>
    </a-modal>
  </div>
</template>
<script>
import {listFile} from '@/api/resource'
import {PlusOutlined} from '@ant-design/icons-vue'

function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  components: {
    PlusOutlined,
  },
  data() {
    return {
      originUrl: 'http://localhost:8099',
      previewVisible: false,
      previewImage: '',
      fileList: []
    }
  },
  created() {
    this.listFile()
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({fileList}) {
      this.fileList = fileList
    },
    listFile() {
      listFile().then(res => {
        console.log(res)
        this.handlerFileList(res.data)
      }).catch(err => {
        console.log(err)
      })
    },
    handlerFileList(data) {
      data.forEach(item => {
        this.fileList.push({
          uid: item.id,
          name: item.name,
          status: 'done',
          url: this.originUrl + item.url
        })
      })
    }
  },
}
</script>
<style>
.ant-upload-select-picture-card i{
  font-size: 32px;
  color: #999999;
}

.ant-upload-select-picture-card .ant-upload-text{
  margin-top: 8px;
  color: #666666;
}
</style>


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值