使用MultipartFile上传文件

单文件上传:

public class UploadFile {

	public String oneFileUpload(HttpServletRequest request, HttpServletResponse response, MultipartFile file) {
		// 储存文件名
		String fileName = null;
		if (file != null) {
			// 获取项目web文件保存路径
			String currentPath = request.getServletContext().getRealPath("/uploadFile/");
			System.out.println("【图片保存路径】:" + currentPath);
			// 如果目录不存在,自动创建文件夹
			File dir = new File(currentPath);
			if (!dir.exists()) {
				dir.mkdir();
				System.out.println("【保存图片的文件夹不存在,新建一个文件夹】");
			}
			try {
				fileName = Upload(currentPath, file);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return fileName;
	}

	public String Upload(String currentPath, MultipartFile file) throws Exception {
		if (file != null) {
			// 文件名后缀
			String fileName = file.getOriginalFilename();
			String suffix = null;
			/**
			 * 【注意!!!】 用indexOf('.')方法截取字符串:
			 * 如果String的indexOf方法返回查找字符在字符串中的位置,但是没找到的话就会返回-1
			 */
			int index = fileName.indexOf('.');
			if (index != -1) {
				suffix = fileName.substring(fileName.indexOf('.'));
				// 上传文件名 生成唯一识别码
				String OriginalFileName = UUID.randomUUID() + suffix;// UUID.randomUUID()
				System.out.println("【上传文件生成唯一识别码】:" + OriginalFileName);
				// 要上传服务器端保存的文件对象 文件保存路径:currentPath 文件名:OriginalFileName
				File serviceFile = new File(currentPath + OriginalFileName);
				file.transferTo(serviceFile); // 将文件写入到服务器端文件内
				return OriginalFileName;
			}
			return null;
		}
		return null;
	}
}

直接调用oneFileUpload()方法就ok

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值