关于前端文件上传后将文件保存至服务器路径存储在数据库并在相应页面展示的总结

2023-10-26

前期准备

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

具体实例展示

1.数据库建表

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

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN"  "sql-map-2.dtd">
<sqlMap>
	<!-- Start -->
	<typeAlias alias="finishwinewl" type="com.qkj.finishwinewl.bean.finishwinewlBean" />
	<select id="finishwinewl_getfinishwinewl" resultClass="finishwinewl" parameterClass="java.util.Map">
	
		<![CDATA[ 
			Select * From qkj_t_finishwinewl
		]]>
		<dynamic prepend="WHERE"><!--所有查询项目-->
		    <isNotNull prepend="AND" property="uuid"><![CDATA[ uuid=#uuid# ]]></isNotNull>
		</dynamic>
	</select>
	<insert id="finishwinewl_addfinishwinewl" parameterClass="finishwinewl">
		<![CDATA[ 
			Insert Into qkj_t_finishwinewl (fid,code,fragrance,detection_info,quality_standard,retail_price,tasting_info,drinking_method,introduction,name,image,report_number)
			Values (#fid#,#code#,#fragrance#,#detection_info#,#quality_standard#,#retail_price#,#tasting_info#,#drinking_method#,#introduction#,#name#,#image#,#report_number#)
		]]>
		<selectKey resultClass="int" keyProperty="uuid">
		<![CDATA[ 
			Select @@IDENTITY
		]]>
		</selectKey>
	</insert>
	<update id="finishwinewl_mdyfinishwinewl" parameterClass="finishwinewl">
		<![CDATA[
			Update qkj_t_finishwinewl
			Set 
		     
		      fid=#fid#,
		      code=#code#,
		      fragrance=#fragrance#,
		      detection_info=#detection_info#,
		      quality_standard=#quality_standard#,
		      retail_price=#retail_price#,
		      tasting_info=#tasting_info#,
		      drinking_method=#drinking_method#,
		      introduction=#introduction#,
		      report_number=#report_number#,
		      name=#name#,
		      image=#image#		    Where uuid = #uuid#
		]]>
	</update>


	<delete id="finishwinewl_delfinishwinewl" parameterClass="finishwinewl">
	<![CDATA[
		Delete From  qkj_t_finishwinewl Where uuid=#uuid#
	]]>
	</delete>
	<!-- End -->
</sqlMap>

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<String, Object> map) {
		return super.list("finishwinewl_getfinishwinewl", map);
	}
	
	public Object get(Object uuid) {
		Map<String, Object> map = new HashMap<String, Object>();
		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<String, Object> map = new HashMap<String, Object>();
	private finishwinewlDao dao = new finishwinewlDao();
	private finishwinewlBean finishwinewl;
	private List<finishwinewlBean> finishwinewls;
	private String message;
	private String viewFlag;
	private int recCount;
	private int pageSize;
	private int currPage;
	private String path = "<a href='/manager/default'>首页</a>&nbsp;&gt;&nbsp;列表";
	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<String, Object> getMap() {
		return map;
	}

	public void setMap(Map<String, Object> 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<finishwinewlBean> getFinishwinewls() {
		return finishwinewls;
	}

	public void setFinishwinewls(List<finishwinewlBean> 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 = "<a href='/manager/default'>首页</a>&nbsp;&gt;&nbsp;列表";
		} 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 = "<a href='/manager/default'>首页</a>&nbsp;&gt;&nbsp;<a href='/finishwinewl/finishwinewl_list?viewFlag=relist'>列表</a>&nbsp;&gt;&nbsp;增加";
			} 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 = "<a href='/manager/default'>首页</a>&nbsp;&gt;&nbsp;<a href='/finishwinewl/finishwinewl_list?viewFlag=relist'>列表</a>&nbsp;&gt;&nbsp;修改产品";
			} 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<imageUpload.length;i++)
					{*/
						//if (imageUpload !=null)
						//{
							String datetime=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
							int x=(int)(Math.random()*100000);
							while(x<10000 || !handle(x))
							{
								x=(int)(Math.random()*100000);
							}
							int ii= fileUploadFileName.indexOf("."); 
			    	        String sExt = fileUploadFileName.substring(ii,fileUploadFileName.length());
			    	        String fileNamel = datetime+String.valueOf(x)+sExt;
			    	        File mm = new File(realpath + File.separator + fileNamel);
			    	        copyFile(fileUpload.toString(), mm.toString());
			    	        UploadRoot=UploadRoot+"\\Imageupload\\" + fileNamel;

			    	        
			    	        //File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");
						//}
					   //}
			 }
			 finishwinewl.setImage(UploadRoot);
			 dao.add(finishwinewl);
		} catch (Exception e) {
			log.error(this.getClass().getName() + "!add 数据添加失败:", e);
			throw new Exception(this.getClass().getName() + "!add 数据添加失败:", e);
		}
		return SUCCESS;
	}

	public String save() throws Exception {
		ContextHelper.isPermit("QKJ_FINISHWINEWL_FINISHWINEWL_MDY");
		try {
			System.out.println("aaa");
			/*finishwinewl.setLm_user(ContextHelper.getUserLoginUuid());
			finishwinewl.setLm_time(new Date());*/
			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 = ServletActionContext.getServletContext().getRealPath("./") + File.separator + "Imageupload";     
			 if (fileUploadFileName != null)
			 {
				         
					//imageUpload = fileUploadFileName.split(",");
					/*for(int i=0;i<imageUpload.length;i++)
					{*/
						//if (imageUpload !=null)
						//{
							String datetime=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
							int x=(int)(Math.random()*100000);
							while(x<10000 || !handle(x))
							{
								x=(int)(Math.random()*100000);
							}
							int ii= fileUploadFileName.indexOf("."); 
			    	        String sExt = fileUploadFileName.substring(ii,fileUploadFileName.length());
			    	        String fileNamel = datetime+String.valueOf(x)+sExt;
			    	        File mm = new File(realpath + File.separator + fileNamel);
			    	        copyFile(fileUpload.toString(), mm.toString());
			    	        UploadRoot=UploadRoot+"\\Imageupload\\" + fileNamel;
			    	        //File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");
						//}
					   //}
			 }
			finishwinewl.setImage(UploadRoot);
			dao.save(finishwinewl);
		} catch (Exception e) {
			log.error(this.getClass().getName() + "!save 数据更新失败:", e);
			throw new Exception(this.getClass().getName() + "!save 数据更新失败:", e);
		}
		return SUCCESS;
	}

	public String del() throws Exception {
		ContextHelper.isPermit("QKJ_FINISHWINEWL_FINISHWINEWL_DEL");
		try {
			dao.delete(finishwinewl);
			setMessage("删除成功!ID=" + finishwinewl.getUuid());
		} catch (Exception e) {
			log.error(this.getClass().getName() + "!del 数据删除失败:", e);
			throw new Exception(this.getClass().getName() + "!del 数据删除失败:", e);
		}
		return SUCCESS;
	}
    
	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;
	}
}

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" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>列表--<s:text name="APP_NAME" /></title>
<s:action name="ref_head" namespace="/manager" executeResult="true" />
</head>
<body>
<!-- 顶部和左侧菜单导航 -->
<s:action name="nav" namespace="/manage" executeResult="true" />
<div class="tab_right">
 	<div class="tab_warp main" >
 	<div class="dq_step">
		${path}
		<c:if test="${it:checkPermit('QKJ_FINISHWINEWL_FINISHWINEWL_ADD',null)==true}">
			<span class="opb lb op-area"><a href="<s:url namespace="/finishwinewl" action="finishwinewl_load"><s:param name="viewFlag">add</s:param></s:url>">添加单据</a></span>
		</c:if>
	</div>
 	<s:form id="serachForm" name="serachForm" action="finishwinewl_list"  method="get" namespace="/finishwinewl" theme="simple">
 	<div class="label_con">
 	<div class="label_main">
  
        <div class="label_hang tac">
            <s:submit value="搜索" /> <s:reset value="重置" />
        </div>
	</div>
 	</div>
 	</s:form>
 	<div class="tab_warp">
		<table>
			<tr id="coltr">
			    <th>物料编码</th>
			    <th>物料名称</th>
			    <th>香型</th>
			    <th>检测信息</th>
			    <th>质量标准</th>
			    <th>零售价</th>
			    <th>品鉴信息</th>
			    <th>建议饮用方式</th>
			    <th>产品介绍</th>
			    <th>检测报告编号</th>
			    <th>操作</th>
			   
			</tr>
			<s:iterator value="finishwinewls" status="sta">
			<tr id="showtr${uuid}">
			    <td>${code}</td>
			    <td>${name}</td>
			    <td>${fragrance}</td>
			    <td>${introduction}</td>
			    <td>${detection_info}</td>
			    <td>${quality_standard }</td>
			    <td>${retail_price}</td>
			    <td>${tasting_info}</td>
			    <td>${drinking_method}</td>
			    <td>${report_number}</td>

				<td class="td4 op-area">			
					<c:if test="${it:checkPermit('QKJ_FINISHWINEWL_FINISHWINEWL_MDY',null)==true}">
			    		<a class="input-blue" href="<s:url namespace="/finishwinewl" action="finishwinewl_load"><s:param name="viewFlag">mdy</s:param><s:param name="finishwinewl.uuid" value="uuid"></s:param></s:url>">修改</a>
			    	</c:if>
			    	<c:if test="${it:checkPermit('QKJ_FINISHWINEWL_FINISHWINEWL_DEL',null)==true}">
			    		<a class="input-red" href="<s:url namespace="/finishwinewl" action="finishwinewl_del"><s:param name="finishwinewl.uuid" value="uuid"></s:param></s:url>" onclick="return isDel();">删除</a>
			    	</c:if>
				</td>
				<td>
				
				
			
				</td>
				<td class="td0 op-area"><a onClick="showDetail('showtr${uuid}');" href="javascript:;" class="input-nostyle">查看</a></td>
			</tr>
			</s:iterator>
	    </table>
	</div>
	
	<div id="listpage" class="pagination"></div>
 </div>
 </div>
<!-- HIDDEN AREA END -->
<s:action name="ref_foot" namespace="/manager" executeResult="true" />
<script type="text/javascript">
$(function(){
	printPagination("listpage",'${currPage}','${recCount}','${pageSize}');
 });
</body>
</html>

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

<%@ 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"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>产品管理--<s:text name="APP_NAME" /></title>
<s:action name="ref_head" namespace="/manager" executeResult="true" />
</head>


<body>
	<s:action name="nav" namespace="/manage" executeResult="true" />
	<div class="tab_right">
		<div class="tab_warp main">
			 <div class="dq_step">
			${path}
			<span class="opb lb op-area"><a href="<s:url namespace="/finishwinewl" action="finishwinewl_list"></s:url>">返回列表</a></span>
		    </div> 
			<s:form id="editForm" name="editForm" cssClass="validForm"
				action="finishwinewl_load" namespace="/finishwinewl" method="post"
				theme="simple" enctype="multipart/form-data">
				<!--<form action="/sysvip/uploadFile" method="post" enctype ="multipart/form-data">-->
				
					<div class="label_hang">
						<div class="label_ltit">fid:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.fid" title="fid"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">物料编码:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.code" title="物料编码"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">香型:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.fragrance" title="香型"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">检测信息:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.detection_info" title="检测信息"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">质量标准:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.quality_standard " title="质量标准"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">零售价:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.retail_price" title="零售价"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">品鉴信息:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.tasting_info" title="品鉴信息"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">建议饮用方式:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.drinking_method" title="建议饮用方式"/>
						</div>
					</div>
				     <div class="label_hang">
						<div class="label_ltit">产品介绍:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.introduction" title="产品介绍"/>
						</div>
					</div>
					 <div class="label_hang">
						<div class="label_ltit">检测报告编号:</div>
						<div class="label_rwben label_rwb">
							<s:textfield name="finishwinewl.report_number" title="产品介绍"/>
						</div>
					</div>
					<s:if test="'mdy' == viewFlag">
						<div class="label_main">
							<div class="label_hang">
								<s:hidden name="finishwinewl.image" title="产品图片路径" />
								<div class="label_ltit">产品图片:
								</div>
									<img src="${finishwinewl.image }" border="0" width="300" height="300" class="imgbox_img" />${image}
							</div>
						</div>
					</s:if> 
					 
					<div class="label_main">
						<div class="label_hang" id="more">
							<div class="label_ltit">产品图片:</div>
							<div class="label_rwben">
								<input type="file" name="fileUpload" title="上传产品图片" />
							</div>
						</div>
					</div>
					

					<div class="label_main">
						<div class="label_hang">
							<div class="label_ltit" style="font-size: 14px;">相关操作:</div>
							<div class="label_rwbenx">
								<span id="message"><s:property value="message" /></span>
								<s:if test="null == finishwinewl && 'add' == viewFlag">
									<c:if test="${it:checkPermit('QKJ_FINISHWINEWL_FINISHWINEWL_ADD',null)==true}">
									
										<s:submit id="add" name="add" value="确定" action="finishwinewl_add"
											class="input-blue" />
									</c:if>
								</s:if>
								<s:elseif test="null != finishwinewl && 'mdy' == viewFlag">
									<c:if
										test="${it:checkPermit('QKJ_FINISHWINEWL_FINISHWINEWL_MDY',null)==true}">
										<s:submit id="save" name="save" value="保存"
											action="finishwinewl_save" class="input-blue" />
									</c:if>
									<c:if
										test="${it:checkPermit('QKJ_FINISHWINEWL_FINISHWINEWL_DEL',null)==true}">
										<s:submit id="delete" name="delete" value="删除"
											action="finishwinewl_del" class="input-red"
											onclick="return isDel();" />
									</c:if>
								</s:elseif>
								<input type="button" class="input-gray" value="返回"
									onclick="linkurl('<s:url action="product_list" namespace="/qkjmanage" />');" />
								
								
								
							</div>
						</div>
					</div>
					<!-- </form>-->
			</s:form>
		</div>
	</div>
	<s:action name="ref_foot" namespace="/manager" executeResult="true" />
</body>
</html>

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

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

1.前端文件如何选择:

<div class="label_main">
						<div class="label_hang" id="more">
							<div class="label_ltit">产品图片:</div>
							<div class="label_rwben">
								<input type="file" name="fileUpload" title="上传产品图片" />
							</div>
						</div>
					</div>

其中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<imageUpload.length;i++)
					{*/
						//if (imageUpload !=null)
						//{
							String datetime=new SimpleDateFormat("yyyyMMddhhmmss").format(new Date());
							int x=(int)(Math.random()*100000);
							while(x<10000 || !handle(x))
							{
								x=(int)(Math.random()*100000);
							}
							int ii= fileUploadFileName.indexOf("."); 
			    	        String sExt = fileUploadFileName.substring(ii,fileUploadFileName.length());
			    	        String fileNamel = datetime+String.valueOf(x)+sExt;
			    	        File mm = new File(realpath + File.separator + fileNamel);
			    	        copyFile(fileUpload.toString(), mm.toString());
			    	        UploadRoot=UploadRoot+"\\Imageupload\\" + fileNamel;
			    	        //File myFile = new File("C:" + File.separator + "tmp" + File.separator, "test.txt");
						//}
					   //}
			 }
			 finishwinewl.setImage(UploadRoot);
			 dao.add(finishwinewl);
		} catch (Exception e) {
			log.error(this.getClass().getName() + "!add 数据添加失败:", e);
			throw new Exception(this.getClass().getName() + "!add 数据添加失败:", e);
		}
		return SUCCESS;
	}

我们随便写一个固定的文件名,主要是后面的.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;得到相对路径并将其存到数据库中。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

关于前端文件上传后将文件保存至服务器路径存储在数据库并在相应页面展示的总结 的相关文章

随机推荐

  • 几种常见的网页布局形式

    关键字 国 匡 三 川 封面型布局 Flash布局 标题文本型布局 框架型布局和变化型布局等 国字布局 也可以称为 同 字型 是一些大型网站所喜欢的类型 即最上面是网站的标题以及横幅广告条 接下来就是网站的主要内容 左右分列两小条内容 中间
  • MOOC 大数据Note

    MOOC 大数据Note Spark Spark 一个软件栈满足不同交互场景 Lineage 血缘关系 创建 转换 动作 ShuffleMapStage Spark的部署和应用方式 RDD操作分为转换 Transformation 和动作
  • PC端,vue。如果检测到企业微信则打开,如果未检测到则跳转下载页。

    首先要引入一份js文件 文件代码如下 function protocolCheck return function e t n r function s o u if n o if t o var a typeof require func
  • 软件测试工程师最常见的面试题!【学到就是赚到】学妹直呼内行

    1 你如何在pocketpc上TEST你的程序 你考虑了哪些方面 2 如果将你的程序的语言扩展到非英语 例如中文 你如何测试 3 给你一个COCAN 你如何测试 解释说就是罐装的可口可乐 4 当你的程序遇到BUG的时候 你选择怎样处理 5
  • 奇怪的语言又增加了,用互联网黑话写代码!

    梦晨 晓查 发自 凹非寺 量子位 报道 公众号 QbitAI 从程序员code到产品经理PPT的生态闭环 终于打通了 如果编程语言里都是 赋能 反哺 抓手 会是啥样 我们不妨先来写个程序看看 赋能 堆叠 fib 抓手 x 细分 x 对齐 0
  • 密码暴力破解

    密码暴力破解 什么是暴力破解 不安全的密码 密码猜解思路 Python暴力破解 BurpSuite暴力破解 DVWA的low等级暴力破解 DVWA的high等级暴力破解 其他暴力破解工具 wfuzz Hydra Medusa msfcons
  • ICIF2023化工展首亮相,宏工科技解决方案助力制造升级

    ICIF China 2023中国国际化工展览会于9月4日 6日在上海新国际博览中心举办 宏工科技携化工物料处理一站式解决方案首次亮相 同化工行业全产业链共叙物料处理自动化未来 宏工科技是一家提供物料处理自动化设备 系统与服务的国家级高新技
  • windows创建、查看软连接

    创建软连接 mklink j 要创建的目录 已存在的目录 查看软连接 cd到所在目录下 使用dir命令即可看到软连接的位置
  • openwrt从入门到精通-开篇

    openwrt应用前景如何 为什么要学习openwrt呢 一个很重要的原因就是 高通等网通芯片厂家给的sdk 就是集成在openwrt里面的 他们直接拿openwrt系统来深度定制自己的芯片sdk 所以 如果你要做网络产品 使用高通等网通类
  • 腾讯、阿里、字节跳动三家公司有何区别!?

    互联网人爱相互跳槽 腾讯和阿里一直相互流动 近两年势头强劲的字节跳动也成为跳槽热门去向 那么在这三家公司工作有什么区别呢 一起来看 旗舰产品 擅长领域 腾讯 是社交领域的霸主 阿里 是电商界的巨头 字节跳动 是内容领域的王者 公司特色 腾讯
  • Spring的xml配置

    Spring的xml依赖注入 文章目录 Spring的xml依赖注入 1 Bean依赖注入方式 1 1 set注入 1 2 构造器注入 2 Bean依赖注入的数据类型 2 1 普通数据的注入 2 2 集合数据类型 List lt Strin
  • 浅谈 防抖和节流

    防抖和节流 是优化高频率执行代码的手段 目的 节约浏览器 服务器的性能 主要方式 减少函数执行的次数 函数防抖 debounce 函数防抖 事件被触发 等待n秒后再执行回调 如果在这n秒内又被触发 则重新计数 防抖的目的 目的是为了让一定时
  • pybind 回调 多线程 异常

    thread代码 int RecvThread SOCKET sockClient py function caminfocall g caminfocall caminfocall py function caminfocall py f
  • quickjs集成mfc的实现

    QuickJS是一个轻量级的JavaScript解释器 可以在各种平台上运行 如果你想在MFC应用程序中使用QuickJS 你可以使用以下方法来实现 下载QuickJS源代码 然后在MFC应用程序中包含QuickJS文件 在MFC应用程序中
  • 操作系统笔记整理 ——目录索引页

    操作系统笔记整理 目录索引页 笔记整理参考书籍 计算机操作系统 第四版 汤小丹等编著 以下笔记整理主要包含了前八章的内容 具体包含的内容会在下面详细说明 笔记尚有许多不足之处 如果大家发现错误还请私信我修改 感谢 目录即链接 点击目录即可跳
  • XML:你真的有必要了解一下我

    对XML的深入浅出 一 概念 二 功能 三 基本语法 四 快速入门 五 组成部分 5 1文档声明 六 约束 6 1 DTD 6 2 Schema 七 解析 7 1 解析XML的方式 7 2常见解析器 八 Jsoup详解 8 1 快速入门 8
  • 第一届全国技能大赛(世赛项目)河北省选拔赛 网络安全项目任务书

    第一届全国技能大赛 世赛项目 河北省选拔赛 网络安全项目任务书 模块A 网络基础构建 网络基础服务搭建 1 第一部分 网络基础构建 2 第二部分 网络基础服务搭建 模块B 网络安全事件响应 数字取证调查和应用程序安全 1 第一部分 网络安全
  • 流程制造行业MES系统的四大应用特点

    MES制造执行系统就是生产加工过程执行系统 该系统可以融合生产规划信息内容及物料 供应 采购和库存等生产现场管理信息内容 根据数据采集系统 然后融合加工过程中的物料 工时 机器设备 人员等信息内容 让生产管理人员对加工过程及进度 建立一个及
  • 如何利用int型变量存放ip值(c语言)

    IP地址 ip地址是一个32位的二进制数 实际上是4个字节 点分十进制表示为 a b c d a b c d的值都是 0 255 例如ip地址 192 168 0 1 就是一个合格ip地址 可以知道a b c d这些字段都是一个无符号字节表
  • 关于前端文件上传后将文件保存至服务器路径存储在数据库并在相应页面展示的总结

    前期准备 1 开发环境及框架的搭建 基于SSH开发框架 2 数据库建表 表应该有一个字段用来存储文件在服务区上的存储路径 3 map xml文件 4 Action xml文件 5 写好实体类及get set 方法 6 DAO层 7 Acti