我用 jspsmart组件 做上传文件,我把图片上传到服务器,但当tomcat部署 Remove 掉项目时 服务器的图片就全没了,这样项目拿到别的机子运行就没有图片,所以我把图片的名字+后缀 保存到数据库 但不知道当项目运行时如何将数据库的图片自动上传到服务器上或者不要保存到数据库,如何把图片直接保存在MyEclipse的项目中的upload的文件夹 ( upload文件夹是保存图片的 )这样就是双份保存 如何做到这是上传的代码:uploadimage.jsp 页面 <%
SmartUpload mySmartUpload=new SmartUpload();
long file_size_max=4000000;
String fileName2="",ext="",testvar="";
String url="upload/";
mySmartUpload.initialize(pageContext);
try{
mySmartUpload.setAllowedFilesList("jpg,gif");
mySmartUpload.upload();
}
catch(Exception e)
{
%>
<script type="text/javascript">
alert("只允许上传.jpg和.gif类型图片文件");
</script>
<%
}
String name=null;
try
{
com.jspsmart.upload.File myFile=mySmartUpload.getFiles().getFile(0);
//若文件不存在则继续
if(myFile.isMissing())
{
%>
<script type="text/javascript"> alert("请选择要上传的文件"); window.location='upload.htm'; </script>
<%
}
else{ //String myFileName=myFile.getFileName(); //取得上载的文件的文件名 ext=myFile.getFileExt(); //取得后缀名 int file_size=myFile.getSize(); String saveurl=""; if(file_size<file_size_max)
{
//更改文件名,取得当前上传时间的毫秒数值 Calendar calendar=Calendar.getInstance(); String filename=String.valueOf(calendar.getTimeInMillis()); name=filename; saveurl=application.getRealPath("/")+url; saveurl+=filename+"."+ext; // 将文件另存到以WEB应用程序的根目录为文件根目录的目录下
myFile.saveAs(saveurl,SmartUpload.SAVE_PHYSICAL);
}
}
}
catch(Exception e)
{ out.print(e.toString()); } //ImageDao是一个图片的dao层
ImageDao imgDao=new ImageDao(); System.out.println(name+"."+ext); //用AddImageName的方法添加一张图片名称到数据库中,不是图片的全路径,是图片名而已
int result=imgDao.AddImageName(name+"."+ext); if(result>0)
{
response.sendRedirect("success.jsp");
}
else
{
out.print("<script language=javascript>alert('添加到数据库失败');</script>");
}
%>upload.jsp 页面
<html>
<head>
<title>掉</title>
<script type="text/javascript">
function checkfile()
{
if(document.form1.file.value==null)
{
alert('去死');
return false;
}
return true;
}
</script>
</head>
<body>
<table border="0" align="center" cellpadding="0" cellspacing="0"><tr><td height="45" align="center" valign="middle">
<form action="uploadimage.jsp" method="post" enctype="multipart/form-data" name="form1" onsubmit="return checkfile()"><input type="file" name="file"><input type="submit" name="Submit" value="上传"></form></td></tr></table>
SmartUpload mySmartUpload=new SmartUpload();
long file_size_max=4000000;
String fileName2="",ext="",testvar="";
String url="upload/";
mySmartUpload.initialize(pageContext);
try{
mySmartUpload.setAllowedFilesList("jpg,gif");
mySmartUpload.upload();
}
catch(Exception e)
{
%>
<script type="text/javascript">
alert("只允许上传.jpg和.gif类型图片文件");
</script>
<%
}
String name=null;
try
{
com.jspsmart.upload.File myFile=mySmartUpload.getFiles().getFile(0);
//若文件不存在则继续
if(myFile.isMissing())
{
%>
<script type="text/javascript"> alert("请选择要上传的文件"); window.location='upload.htm'; </script>
<%
}
else{ //String myFileName=myFile.getFileName(); //取得上载的文件的文件名 ext=myFile.getFileExt(); //取得后缀名 int file_size=myFile.getSize(); String saveurl=""; if(file_size<file_size_max)
{
//更改文件名,取得当前上传时间的毫秒数值 Calendar calendar=Calendar.getInstance(); String filename=String.valueOf(calendar.getTimeInMillis()); name=filename; saveurl=application.getRealPath("/")+url; saveurl+=filename+"."+ext; // 将文件另存到以WEB应用程序的根目录为文件根目录的目录下
myFile.saveAs(saveurl,SmartUpload.SAVE_PHYSICAL);
}
}
}
catch(Exception e)
{ out.print(e.toString()); } //ImageDao是一个图片的dao层
ImageDao imgDao=new ImageDao(); System.out.println(name+"."+ext); //用AddImageName的方法添加一张图片名称到数据库中,不是图片的全路径,是图片名而已
int result=imgDao.AddImageName(name+"."+ext); if(result>0)
{
response.sendRedirect("success.jsp");
}
else
{
out.print("<script language=javascript>alert('添加到数据库失败');</script>");
}
%>upload.jsp 页面
<html>
<head>
<title>掉</title>
<script type="text/javascript">
function checkfile()
{
if(document.form1.file.value==null)
{
alert('去死');
return false;
}
return true;
}
</script>
</head>
<body>
<table border="0" align="center" cellpadding="0" cellspacing="0"><tr><td height="45" align="center" valign="middle">
<form action="uploadimage.jsp" method="post" enctype="multipart/form-data" name="form1" onsubmit="return checkfile()"><input type="file" name="file"><input type="submit" name="Submit" value="上传"></form></td></tr></table>
解决方案 »
- 错误Http status 500----java.sql.Date.valueOf(Unknown Source)
- 菜鸟--继续报弱智错java.lang.NullPointerException求解!!!
- 请教一个JSP下拉列表问题
- ssh2的事物配置
- jfreechart的高手们救救小弟吧!在线等~~~~~~~急
- RowSet 不能存放CLOB的值吗?
- oracle可不可以跟踪数据表
- 本人想换工作
- 一个低级问题求助!
- 因为上网,不知那个网站把我的注册表改了,我现在不能修改注册表了,说注册表被管理员禁用,这怎么办?
- jdbctemplate 如何让它返回自增id
- 有个操作图片的需求,希望有人能指教!小弟很着急用///
这个让我有点明白了 那如何获得当前 导入myeclipse中的项目的路径啊 假设我现在在随便的机子的myeclipse中导入而我不知道
他的workspace在那个路径如何获得 整个项目的全路进
他的workspace在那个路径如何获得 整个项目的全路进
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
你刚才教我 项目-右键-属性,能看到项目路径但String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";不对啊 获取是这样的 http://localhost:8080/Uppass/upload/ 图片都不知道上哪了
dir="D:\\os\\newproject\\GrpRWeb\\WebContent\\UploadImages";
dir+"/"+ + imageFileName;
或者dir=ServletActionContext.getServletContext().getRealPath("/UploadImages")
dir = request.getSession(true).getServletContext().getRealPath("/UploadImages");
你就不能变通下,上边给你的是struts2的
dir="D:\\os\\newproject\\GrpRWeb\\WebContent\\UploadImages";这个也不好使?
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.upload.web.form;import javax.servlet.http.HttpServletRequest;import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;/**
* MyEclipse Struts Creation date: 08-16-2009
*
* XDoclet definition:
*
* @struts.form name="uploadForm"
*/
public class UploadForm extends ActionForm {
/*
* Generated fields
*/ /** theFile property */
private FormFile theFile; /*
* Generated Methods
*/ /**
* Method validate
*
* @param mapping
* @param request
* @return ActionErrors
*/
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) { System.out.println(theFile.getContentType());
ActionErrors errors = new ActionErrors();
if (theFile.getFileName() == null
|| theFile.getFileName().trim().length() < 1) {
errors.add("fileNull", new ActionMessage("upload.null.error"));
}
// 判断文件的类型
// image/GIF
else if (!theFile.getContentType().startsWith("image")) {
errors.add("badFile", new ActionMessage("upload.bad.error"));
} return errors;
} /**
* Method reset
*
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
// TODO Auto-generated method stub
} /**
* Returns the theFile.
*
* @return FormFile
*/
public FormFile getTheFile() {
return theFile;
} /**
* Set the theFile.
*
* @param theFile
* The theFile to set
*/
public void setTheFile(FormFile theFile) {
this.theFile = theFile;
}
}
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.upload.web.action;import java.io.File;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;public class DownAction extends DownloadAction { @Override
protected StreamInfo getStreamInfo(ActionMapping mapping,
ActionForm actionForm, HttpServletRequest request,
HttpServletResponse response) throws Exception { // 1.设置响应的内容类型为下载
response.setContentType("application/x-msdownload;charset=GBK");
HttpSession session = request.getSession();
String file = (String) session.getAttribute("FILE");
String fileName = file.substring(file.lastIndexOf("/"));
fileName = fileName.substring(1);
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName); File f = new File(file); String contentType = (String) session.getAttribute("CONTENT"); return new FileStreamInfo(contentType, f);
}
}
/*
* Generated by MyEclipse Struts
* Template path: templates/java/JavaClass.vtl
*/
package com.upload.web.action;import java.io.FileOutputStream;
import java.util.UUID;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;import com.upload.web.form.UploadForm;public class UploadAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
UploadForm uploadForm = (UploadForm) form;
// 1.获得保存上传文件绝对路径
String path = servlet.getServletContext().getRealPath("/userFile"); // 2.获得用户上传的文件名
FormFile theFile = uploadForm.getTheFile();
String fileName = theFile.getFileName(); String houzhui = fileName.substring(fileName.lastIndexOf(".")); path += "/" + UUID.randomUUID() + houzhui; HttpSession session = request.getSession();
session.setAttribute("FILE", path);
session.setAttribute("CONTENT", theFile.getContentType()); // 3.文件输出流,向指定的文件输出信息(写出)
FileOutputStream fout = new FileOutputStream(path); // 4.获得用户上传文件的数据
byte fileData[] = theFile.getFileData(); // 5.上传
fout.write(fileData); return mapping.findForward("toDown");
}
}
<%@ page contentType="text/html; charset=GBK"%><%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles"%><html>
<head>
<title>文件上传</title>
</head> <body bgcolor="#CCCCCC">
<h2>
Struts文件上传
</h2>
<hr />
<html:errors/>
<!-- 注意:
1.表单必须包含encType属性,且值为:multipart/form-data
-->
<html:form action="upload" enctype="multipart/form-data">
请选择您要上传的文件:
<html:file property="theFile" />
<html:submit value="上传" /> </html:form>
</body>
</html>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles"%>
<html>
<head>
<title>Struts文件下载</title>
</head> <body>
<h2>
Struts文件下载
</h2>
<hr /> <a href="down.do">下载到客户端</a>
<a href="down.do">在线打开</a> </body>
</html>
不过不建意议你这么做,你只需要把需要首次加载的文件放在images(工作空间)里就行了,上传来的文件单独放到一个文件夹里比如叫upload(tomcat)。如果你还想要你的这些上传后的文件,那你就得多费一点事,把这个文件夹拷到webRoot(工作空间)下,下一次tomcat会自动给你布暑上去的。