车段子项目-SSH上传文件

引言

前段时间做的一个车段子项目,里面有上传图片,txt文档,apk文件等等功能。原先做ITOO的时候也有过导入导出的功能,原理大概就是差不多的,不过那时候是封装好的,一直没有理清楚,现在做这个项目的时候必须自己亲手做,所以理了一下,逻辑理清楚了,其实是非常好做的。


逻辑分析

上传图片主要分为这么几个过程:


1.获取file文件以及他们的的名字。

2.为了保存这些文件并且防止名字重复,所以给文件重新命名。

3.定义一个自己想要保存文件的路径

4.然后上传到指定路径中


实例

我们项目中好多地方用到了上传图片,txt文档或者apk的功能,因此我们把上传文件功能单独提出来放到了工具类里,用到了就直接调用就可以。

上传文件封装类:

public class AddProMsgUntil {

	/**给图片或其他文件重命名*/
	private String getNewName(String fileName)  {   
		
	        int pos = fileName.lastIndexOf( "." );   
	        String nameH = fileName.substring(pos); 
	        SimpleDateFormat sdf =   new SimpleDateFormat("yyyyMMddHHmmss" );
	        String t = sdf.format(new Date().getTime()).toString();
	        int x=(int)(Math.random()*9000+1000);
	        String newName = t+x+nameH;
	        return newName;   
	} 
	
	/**上传图片或其他文件*/
	public String uploadFile(File file,String fileName){
		// 获取当前路径
		String savePath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("");
		if(img != null){
			//给图片或其他文件重命名
			String newName = this.getNewName(fileName);
			//相对路径
			String pathString = "/statics/headimg/"+ newName;
			String proSavePath = savePath + pathString;//绝对路径到某个文件夹下
			String pathagainString="/headimg/"+ newName;
			// 获取上传文件完整路径:文件路径和名称
			File file = new File(proSavePath);
			try {
				//上传到指定位置
				FileUtils.copyFile(img, file);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return pathagainString;
		}else {
			return "";
		}
	}
}

调用类

/**
	 * 上传头像
	 * 
	 * @return
	 */
	//上传文件名字,规定文件名字file+后缀FileName
	private String fileFileName;
	// 头像地址文件
	private File file;
	public String uploadHead() {
			if (file != null) {
				AddProMsgUntil aUntil = new AddProMsgUntil();
				// 获取保存路径
				String picPath = aUntil.uploadImg(file, fileFileName);
				// 把路径保存到数据库中。
				this.siteUsersManager.updateImage(uid, picPath);
			}
	}
	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

注意:在SSH框架中获取file文件,文件名字定义是有规定的,界面上(JSP)文件名字必须跟后台获取的文件名字一样。


结束语

做之前先要明白原理,然后就容易多了。

在项目中确实很锻炼人的逻辑思维能力和解决问题能力。好好锻炼吧




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 22
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值