引言
前段时间做的一个车段子项目,里面有上传图片,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中)文件名字必须跟后台获取的文件名字一样。
结束语
做之前先要明白原理,然后就容易多了。
在项目中确实很锻炼人的逻辑思维能力和解决问题能力。好好锻炼吧