上传文件到服务器并将文件路径存入数据库

在做练手项目的时候总有需要上传文件的功能点,如何简单快捷的实现呢?

首先,我们需要将下面的类引入你的项目,新建一个config包放进去就好。

public class FileUtil {
	public static String upload( MultipartFile mFile,HttpServletRequest request){
		SimpleDateFormat yformat = new SimpleDateFormat("yyyy");
		SimpleDateFormat mformat = new SimpleDateFormat("MM");
		SimpleDateFormat dformat = new SimpleDateFormat("dd");
		Date nowTime = new Date();
		String year = yformat.format(nowTime);
		String month = mformat.format(nowTime);
		String day = dformat.format(nowTime);
		String SavePath = request.getSession().getServletContext().getRealPath(
				"/")
				+ File.separator + "files/" + year + "_" + month+"_"+day+"/";
		File directory = new File(SavePath);
		if(!directory.exists()){
			directory.mkdirs();
		}
		String SaveUrl = "/files/" + year + "_" + month+"_"+day+"/";
		Date dt = new Date();
		Random random = new Random();
		//文件重新命名
		String FileNameAuto = String.format("%X_%X", new Object[] {
				new Integer((int) (dt.getTime())),
				new Integer(random.nextInt()) });
		String name= mFile.getOriginalFilename();  
		int pos = name.lastIndexOf(".");
		//获取文件名后缀Fi
		String ext = name.substring(pos);
		String baseName=FileNameAuto+ext;
		OutputStream outputStream =null;
		try {
			outputStream = new FileOutputStream(SavePath+baseName);
			FileCopyUtils.copy(mFile.getInputStream(), outputStream);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				if(outputStream!=null){
					outputStream.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return SaveUrl+baseName;
	}
	
	//删除
	public static void deleteFile(HttpServletRequest request,String filename){
		String f = request.getSession().getServletContext().getRealPath(
				"/")+filename;
		File file = new File(f);
		file.delete();
	}
	
}

简要描述一下上面类的作用:
    首先,传入文件对象和request对象,upload方法会返回修改后的文件名和拼接好的文件路径返回给你,你就可以将这个地址放在数据库中,在用的时候拿出来直接展示。
    然后当你要删除这个文件的时候,就调用deleteFile方法,将刚刚的文件路径和request对象传过来即可,存储在服务器的文件就会被删除。

这时候,单单引入这一个类直接使用还是实现不了的,还有以下的注意点:

  1. 在实体类中要加入文件属性:MultipartFile uploadFile;
  2. 在form表单提交处,要加上enctype=“multipart/form-data”
  3. 使用时调用该方法(upload),得到图片地址,然后将该地址存入数据库,展示的时候直接展示图片的地址即可。
  4. 当你要删除图片时,将从数据库中查到的图片路径传入方法(deleteFile),则可将存储于服务器的文件删除。

没有一句废话,以上!

你可能感兴趣的:(JavaEE系列)