博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
关于前端文件上传后将文件保存至服务器路径存储在数据库并在相应页面展示的总结
阅读量:4180 次
发布时间:2019-05-26

本文共 12879 字,大约阅读时间需要 42 分钟。

前期准备

1.开发环境及框架的搭建。(基于SSH开发框架)

2.数据库建表,表应该有一个字段用来存储文件在服务区上的存储路径。
3.map.xml文件
4.Action.xml文件
5.写好实体类及get()set()方法
6.DAO层
7.Action()实现,Action()里面需要实现文件的上传服务器功能和路径存储数据库功能。
8.前端页面,前端页面需要实现文件的选择功能。

具体实例展示

1.数据库建表

SQLsever可视化工具

其中image字段用来存储文件在服务器上的存储路径。
2.增删查改(map.xml文件)

3.dao层

package com.qkj.finishwinewl.dao;import java.util.HashMap;import java.util.List;import java.util.Map;import org.iweb.sys.AbstractDAO;/** * @author xiaoyan * */public class finishwinewlDao extends AbstractDAO{    public List list(Map
map) { return super.list("finishwinewl_getfinishwinewl", map); } public Object get(Object uuid) { Map
map = new HashMap
(); map.put("uuid", uuid); return super.get("finishwinewl_getfinishwinewl", map); } public Object add(Object parameters) { return super.add("finishwinewl_addfinishwinewl", parameters); } public int save(Object parameters) { return super.save("finishwinewl_mdyfinishwinewl", parameters); } public int delete(Object parameters) { return super.delete("finishwinewl_delfinishwinewl", parameters); } public int getResultCount() { return super.getResultCount(); } }

4.Action实现

package com.qkj.finishwinewl.action;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;import org.apache.commons.logging.Log;import org.apache.commons.logging.LogFactory;import org.apache.struts2.ServletActionContext;import org.iweb.sys.ContextHelper;import org.iweb.sys.Parameters;import org.iweb.sys.ToolsUtil;import com.opensymphony.xwork2.ActionSupport;import com.qkj.finishwinewl.dao.finishwinewlDao;import com.qkj.finishwinewl.bean.finishwinewlBean;/** * @author yanluhai  * */public class finishwinewlAction extends ActionSupport{	private static final long serialVersionUID = 1L;	private static Log log = LogFactory.getLog(finishwinewlAction.class);	private Map
map = new HashMap
(); private finishwinewlDao dao = new finishwinewlDao(); private finishwinewlBean finishwinewl; private List
finishwinewls; private String message; private String viewFlag; private int recCount; private int pageSize; private int currPage; private String path = "
首页 > 列表"; private String [] imageUpload; private File fileUpload; private String fileUploadFileName; // 文件名+FileName public File getFileUpload() { return fileUpload; } public void setFileUpload(File fileUpload) { this.fileUpload = fileUpload; } public static Log getLog() { return log; } public static void setLog(Log log) { finishwinewlAction.log = log; } public Map
getMap() { return map; } public void setMap(Map
map) { this.map = map; } public finishwinewlDao getDao() { return dao; } public void setDao(finishwinewlDao dao) { this.dao = dao; } public finishwinewlBean getFinishwinewl() { return finishwinewl; } public void setFinishwinewl(finishwinewlBean finishwinewl) { this.finishwinewl = finishwinewl; } public List
getFinishwinewls() { return finishwinewls; } public void setFinishwinewls(List
finishwinewls) { this.finishwinewls = finishwinewls; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public String getViewFlag() { return viewFlag; } public void setViewFlag(String viewFlag) { this.viewFlag = viewFlag; } public int getRecCount() { return recCount; } public void setRecCount(int recCount) { this.recCount = recCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrPage() { return currPage; } public void setCurrPage(int currPage) { this.currPage = currPage; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String[] getImageUpload() { return imageUpload; } public void setImageUpload(String[] imageUpload) { this.imageUpload = imageUpload; } public String getFileUploadFileName() { return fileUploadFileName; } public void setFileUploadFileName(String fileUploadFileName) { this.fileUploadFileName = fileUploadFileName; } public static long getSerialversionuid() { return serialVersionUID; } public String list() throws Exception { ContextHelper.isPermit("QKJ_FINISHWINEWL_FINISHWINEWL_LIST"); try { map.clear(); if (finishwinewl == null) finishwinewl = new finishwinewlBean(); ContextHelper.setSearchDeptPermit4Search("QKJ_FINISHWINEWL_FINISHWINEWL_LIST", map, "apply_depts", "apply_user"); ContextHelper.SimpleSearchMap4Page("QKJ_FINISHWINEWL_FINISHWINEWL_LIST", map, finishwinewl, viewFlag); this.setPageSize(ContextHelper.getPageSize(map)); this.setCurrPage(ContextHelper.getCurrPage(map)); this.setFinishwinewls(dao.list(map)); this.setRecCount(dao.getResultCount()); path = "
首页 > 列表"; } catch (Exception e) { log.error(this.getClass().getName() + "!list 读取数据错误:", e); throw new Exception(this.getClass().getName() + "!list 读取数据错误:", e); } return SUCCESS; } public String load() throws Exception { try { if (null == viewFlag) { this.setFinishwinewl(null); setMessage("你没有选择任何操作!"); } else if ("add".equals(viewFlag)) { this.setFinishwinewl(null); path = "
首页 > 
列表 > 增加"; } else if ("mdy".equals(viewFlag)) { if (!(finishwinewl == null || finishwinewl.getUuid() == null)) { this.setFinishwinewl((finishwinewlBean) dao.get(finishwinewl.getUuid())); System.out.println(finishwinewl.getImage()); } else { this.setFinishwinewl(null); } path = "
首页 > 
列表 > 修改产品"; } else { this.setFinishwinewl(null); setMessage("无操作类型!"); } } catch (Exception e) { log.error(this.getClass().getName() + "!load 读取数据错误:", e); throw new Exception(this.getClass().getName() + "!load 读取数据错误:", e); } return SUCCESS; } public String add() throws Exception { ContextHelper.isPermit("QKJ_FINISHWINEWL_FINISHWINEWL_ADD"); try { /*finishwinewl.setAdd_user(ContextHelper.getUserLoginUuid()); finishwinewl.setAdd_time(new Date());*/ //String c = fileUpload.getParent(); //File mm = new File(c + File.separator + fileUploadFileName); //copyFile(fileUpload.toString(), mm.toString()); fileUploadFileName="9FBA2651-8851-4a92-88C7-36BDA03856E9.png"; String UploadRoot=""; String t=Thread.currentThread().getContextClassLoader().getResource("").getPath(); //int num=t.indexOf(".metadata"); //String realpath=t.substring(1,num).replace('/', '\\')+"yxzx\\WebContent\\Imageupload"; // String realpath = ServletActionContext.getServletContext().getRealPath("./") + File.separator + "Imageupload"; // String realpath = "u01/wwwhome/Imageupload"; //String realpath = "u01" + File.separator +"wwwhome" + File.separator +"Imageupload"; //String realpath = "E:\\hhh\\kk"; String realpath = ServletActionContext.getServletContext().getRealPath("./") + File.separator + "Imageupload"; if (fileUploadFileName != null) { //imageUpload = fileUploadFileName.split(","); /*for(int i=0;i

5.前端页面

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="s" uri="/struts-tags"%><%@ taglib prefix="it" uri="http://qkjchina.com/iweb/iwebTags" %>
列表--<s:text name="APP_NAME" />
物料编码 物料名称 香型 检测信息 质量标准 零售价 品鉴信息 建议饮用方式 产品介绍 检测报告编号 操作
${code} ${name} ${fragrance} ${introduction} ${detection_info} ${quality_standard } ${retail_price} ${tasting_info} ${drinking_method} ${report_number}
mdy
">修改
" onclick="return isDel();">删除
查看

此页用列表的方式展示相应信息

<%@ page language="java" contentType="text/html; charset=UTF-8"	pageEncoding="UTF-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%><%@ taglib prefix="s" uri="/struts-tags"%><%@ taglib prefix="it" uri="http://qkjchina.com/iweb/iwebTags"%>
产品管理--<s:text name="APP_NAME" />
${path}
">返回列表
fid:
物料编码:
香型:
检测信息:
质量标准:
零售价:
品鉴信息:
建议饮用方式:
产品介绍:
检测报告编号:
产品图片:
${image}
产品图片:
相关操作:
');" />

在这里插入图片描述

最终可以看到我们上传的各项数据及文件(以图片为例)展示在页面上。
明细页实现前端收集数据和展示文件的功能

接下来介绍实现文件上传的几个关键点

1.前端文件如何选择:

产品图片:

其中fileUpload暂存上传的文件,

在这里插入图片描述
在后端代码中定义file 类型的fileUpload,写好它的get(),set()方法,想象一下我们已经在前端将一个文件传到现在的后端fileUpload中,现在要做的是将文件上传到服务器指定文件夹或者项目的某个文件夹中,要将这个路径存放到我们的数据库相应字段下面。
下面实现的就是将文件上传到项目文件夹以及将路径存储到数据库的过程。

public String add() throws Exception {		ContextHelper.isPermit("QKJ_FINISHWINEWL_FINISHWINEWL_ADD");		try {			 			  			/*finishwinewl.setAdd_user(ContextHelper.getUserLoginUuid());			finishwinewl.setAdd_time(new Date());*/			//String c = fileUpload.getParent();			//File mm = new File(c + File.separator + fileUploadFileName);			//copyFile(fileUpload.toString(), mm.toString());			  			fileUploadFileName="9FBA2651-8851-4a92-88C7-36BDA03856E9.png";			String UploadRoot="";			String t=Thread.currentThread().getContextClassLoader().getResource("").getPath();		  			String realpath = ServletActionContext.getServletContext().getRealPath("./") + File.separator + "Imageupload";			 if (fileUploadFileName != null)			 {				         					//imageUpload = fileUploadFileName.split(",");					/*for(int i=0;i

我们随便写一个固定的文件名,主要是后面的.png等文件类型,并获取文件即将上传的项目文件夹的路径,并在该文件夹下面建一个图片,将我们上传的图片通过copfile函数覆盖创建在项目文件夹下面的那个图片

public static void copyFile(String oldPath, String newPath)	{		try {			int bytesum = 0;			int byteread = 0;			File oldfile = new File(oldPath);			System.out.println("oldPath:"+oldPath);			System.out.println("newPath:"+newPath);			if (oldfile.exists()) 			{ // 文件存在时				InputStream inStream = new FileInputStream(oldPath); // 读入原文件				FileOutputStream fs = new FileOutputStream(newPath);				byte[] buffer = new byte[1444];				int length;				while ((byteread = inStream.read(buffer)) != -1)				{					bytesum += byteread; // 字节数 文件大小					System.out.println(bytesum);					fs.write(buffer, 0, byteread);				}				inStream.close();			}		} catch (Exception e) 		{			System.out.println("复制单个文件操作出错");			e.printStackTrace();		}	}		public static boolean handle(int n)//这里只是得到一个随机的数字	{		int[] list=new int[5];		for(int i=0;i<5;i++)		{			list[i]=n%10;			n=n/10;		}		for(int i=0;i<5;i++)		{			for(int j=i+1;j<5;j++)			{				if(list[i]==list[j]) return false;			}		}		return true;	}

UploadRoot=UploadRoot+"\Imageupload\" + fileNamel;得到相对路径并将其存到数据库中。

转载地址:http://grlai.baihongyu.com/

你可能感兴趣的文章
高性能服务器设计
查看>>
图文介绍openLDAP在windows上的安装配置
查看>>
Pentaho BI开源报表系统
查看>>
Pentaho 开发: 在eclipse中构建Pentaho BI Server工程
查看>>
android中SharedPreferences的简单例子
查看>>
android中使用TextView来显示某个网址的内容,使用<ScrollView>来生成下拉列表框
查看>>
andorid里关于wifi的分析
查看>>
Hibernate和IBatis对比
查看>>
Spring MVC 教程,快速入门,深入分析
查看>>
Android 的source (需安装 git repo)
查看>>
Ubuntu Navicat for MySQL安装以及破解方案
查看>>
java多线程中的join方法详解
查看>>
在C++中如何实现模板函数的外部调用
查看>>
HTML5学习之——HTML 5 应用程序缓存
查看>>
HTML5学习之——HTML5 内联 SVG
查看>>
HTML5学习之——HTML 5 服务器发送事件
查看>>
SVG学习之——HTML 页面中的 SVG
查看>>
SVG 形状学习之——SVG圆形
查看>>
SVG 滤镜学习之——SVG 滤镜
查看>>
mysql中用命令行复制表结构的方法
查看>>