然后把图片的路径名作为varchar型保存到数据库中。显示的时候就到数据库中查找路径名,处理后赋值给<img>的src属性
然后是同过IO流把图片作为文件保存到服务器某个文件夹,例如upload文件夹.
具体怎么实现,哪位大侠可以解答一下吗?谢谢!
25 个解决方案
#1
感覺你已經說的很詳細了,LZ不是有思路了嗎?
#2
用struts的标签实现,具体你google一下。
#3
我是想到这个大概思路的,但是具体怎么实现还是很模糊!我上了google搜一下,有用common-fileupload实现的 但是很多地方不清楚。能具体一点就好了。
#4
类中要有这三个属性
private File upload;
private String uploadContentType;
private String uploadFileName;
页面
<input name="upload" type="file" class="input_style2" id="upload" size="30" />
处理逻辑:
File picFile = new File(this.getRealPath() + "/**");
if (!picFile.exists()) {
picFile.mkdirs();
}
String fileReName = this.getUploadFileName() + "." + getUploadSuffix(类的实例.getUploadFileName());
类的实例.getUpload().renameTo(new File(picFile.getPath(), fileReName));
private File upload;
private String uploadContentType;
private String uploadFileName;
页面
<input name="upload" type="file" class="input_style2" id="upload" size="30" />
处理逻辑:
File picFile = new File(this.getRealPath() + "/**");
if (!picFile.exists()) {
picFile.mkdirs();
}
String fileReName = this.getUploadFileName() + "." + getUploadSuffix(类的实例.getUploadFileName());
类的实例.getUpload().renameTo(new File(picFile.getPath(), fileReName));
#5
public static String upload(String path, FormFile formFile, String filename) throws Exception {
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
// 取欲上传的文件的名字和长度
String fname = formFile.getFileName();
String randomStr = Integer.toString((int)(Math.random()*1000));
// 将上传时间加入文件名
int i = fname.indexOf(".");
//String name = String.valueOf(date.getTime());
String name = format.format(date);
String type = fname.substring(i + 1);
if(filename == null || filename.equals("")){
fname = name +"_"+randomStr+ "." + type;
}else{
fname = name +"_"+randomStr +"_" + filename + "." + type;
}
InputStream streamIn = formFile.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
if (!uploadFile.exists() || uploadFile == null) { // 判断指定路径是否存在,不存在则创建路径
uploadFile.mkdirs();
}
String path = uploadFile.getPath() + "\\" + fname;
//System.out.println("内 :"+path);
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.flush();
streamOut.close();
streamIn.close();
formFile.destroy();
return fname;
}
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
// 取欲上传的文件的名字和长度
String fname = formFile.getFileName();
String randomStr = Integer.toString((int)(Math.random()*1000));
// 将上传时间加入文件名
int i = fname.indexOf(".");
//String name = String.valueOf(date.getTime());
String name = format.format(date);
String type = fname.substring(i + 1);
if(filename == null || filename.equals("")){
fname = name +"_"+randomStr+ "." + type;
}else{
fname = name +"_"+randomStr +"_" + filename + "." + type;
}
InputStream streamIn = formFile.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
if (!uploadFile.exists() || uploadFile == null) { // 判断指定路径是否存在,不存在则创建路径
uploadFile.mkdirs();
}
String path = uploadFile.getPath() + "\\" + fname;
//System.out.println("内 :"+path);
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.flush();
streamOut.close();
streamIn.close();
formFile.destroy();
return fname;
}
#6
学习了。。。
#7
struts2 有专门的上传文件的
#8
你这个把图片的本地路径保存在数据库,显示的时候赋给img的src属性是不可行的!
客户端在不同机器,你能保证他e盘下都有那张图片?感觉lz的思路有偏差!
图片路径你得采用图片保存在服务器上的路径,相对绝对随你,至于图片怎么上传的,网上资料很多
客户端在不同机器,你能保证他e盘下都有那张图片?感觉lz的思路有偏差!
图片路径你得采用图片保存在服务器上的路径,相对绝对随你,至于图片怎么上传的,网上资料很多
#9
LZ 去看看把
http://www.javaeye.com/wiki/Struts2_leader_guide/1986-struts_guide_10
http://www.javaeye.com/wiki/Struts2_leader_guide/1986-struts_guide_10
#10
if (null != this.getPhotoFile()) {
// 从画面上取得图片文件
File files = this.getPhotoFile();
// 文件名 = 文件名 + 日期
photoFileFileName = new Date().getTime() + photoFileFileName.trim();
String path = ServletActionContext.getServletContext().getRealPath("/");
if (!path.endsWith("\\")) {
path = path + "\\";
}
String savePath = path + "\\UploadImages\\";
// 判断保存用文件夹是否存在
mkdir(savePath);
// 保存用的数据流生成
FileOutputStream fos = null;
FileInputStream fis = null;
try {
// 保存用的数据流生成
fos = new FileOutputStream(savePath + photoFileFileName);
System.out.println(savePath + photoFileFileName);
// 保存文件
fis = new FileInputStream(files);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
cond.setPhotoPath(savePath+photoFileFileName);
} catch (FileNotFoundException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}
}
}else{
cond.setPhotoPath(null);
}
// 从画面上取得图片文件
File files = this.getPhotoFile();
// 文件名 = 文件名 + 日期
photoFileFileName = new Date().getTime() + photoFileFileName.trim();
String path = ServletActionContext.getServletContext().getRealPath("/");
if (!path.endsWith("\\")) {
path = path + "\\";
}
String savePath = path + "\\UploadImages\\";
// 判断保存用文件夹是否存在
mkdir(savePath);
// 保存用的数据流生成
FileOutputStream fos = null;
FileInputStream fis = null;
try {
// 保存用的数据流生成
fos = new FileOutputStream(savePath + photoFileFileName);
System.out.println(savePath + photoFileFileName);
// 保存文件
fis = new FileInputStream(files);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
cond.setPhotoPath(savePath+photoFileFileName);
} catch (FileNotFoundException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}
}
}else{
cond.setPhotoPath(null);
}
#11
#12
用cos上传组件
下载地址 http://www.servlets.com/cos/index.html
下载链接 http://www.servlets.com/cos/cos-26Dec2008.zip
upload.html
<html>
<head>
<title>upload</title>
<script type="text/javascript" src="./javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="./javascript/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('ok');
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>
<body scroll="no">
<center>
<form id="uploadimage" name="uploadimage" method="post"
action="./upload.jsp?folderName=uploadImage&relativePath=../../"
>
<table width=600 border=0 align="center" cellPadding=0 cellSpacing=0
id="table1" frame="void" style="BORDER-LEFT: #ffffff 0px solid;">
<input type=hidden id="UploadIsSucces" value="0" />
<tr bgcolor="#FFFFFF">
<td width="100" align="center">
选择图片
</td>
<td width="490" colspan="3" rowspan="2">
<input type="file" name="upimage" id="upimage" size="30">
<input type="text" name="imgdes" id="imgdes" size="40">
</td>
</tr>
<tr bgcolor="#FFFFFF">
<td align="center">
图片描述
</td>
</tr>
<tr>
<td>
<input type="submit" id="sub" value="submit" />
<br />
<a href="#" id="testJS">testJS</a>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
-----------------------------------------------华丽分割线--------------------------------------------------------------------
upload.jsp
<%@ page contentType="text/html; charset=gbk" language="java" errorPage="" %>
<%@ page language="java" import="java.io.PrintWriter"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.util.UUID"%>
<%@ page language="java" import="java.util.Enumeration"%>
<%@ page language="java" import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.FileRenamePolicy"%>
<%
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("gbk");
PrintWriter xmlout = response.getWriter();
String uuid = UUID.randomUUID().toString();
//文件的fileURL
String fileURL = "";
// 上传文件名
String fileName = null;
//取得文件描述
String fileDesName = "";
StringBuffer sb = new StringBuffer();
String result = "";
try
{
//得到此源文件的目录
String realPath = getServletContext().getRealPath("");
String contentPath = request.getContextPath();
String requestURL = request.getRequestURL().toString();
String realURL = requestURL.split(contentPath)[0] + contentPath;
//上传文件存放的文件夹名称,一律放在根目录下的文件夹里面即folderName/
String folderName = request.getParameter("folderName");
//根据不同层级../../的路径不同
String relativePath = request.getParameter("relativePath");
//文件的相对路径
String comparafileName = "";
// 将上传文件存放在saveDirectory
String saveDirectory = realPath + "/" + folderName;
System.out.println("saveDirectory= " + saveDirectory);
File uploadPath = new File(saveDirectory);
if (!uploadPath.exists())
{
uploadPath.mkdir();
}
// 上传文件的大小限制在10 MB
int maxPostSize = 10 * 1024 * 1024;
//实现将上传文件更名,以防同名覆盖和同时上传两个文件名相同的文件,自动在文件名后面加1(在1~9999范围内)
FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();
// 上传文件
MultipartRequest multi = new MultipartRequest(request,saveDirectory, maxPostSize, "GBK",policy);
StringBuffer filenametemp = new StringBuffer();
filenametemp.append(uuid);
//在iidd后面加一下划线"-"以便和文件名称区分出来
filenametemp.append("-");
//取得文件描述
fileDesName = multi.getParameter("imgdes");
//System.out.println("文件描述:"+ fileDesName);
// 取得所有上传文件名称
Enumeration filesname = multi.getFileNames();
while (filesname.hasMoreElements())
{
String name = (String) filesname.nextElement();
//文件上传的完整路径
File f = multi.getFile(name);
//文件名称
fileName = multi.getFilesystemName(name);
if (fileName != null)
{
String oldFilename=fileName;
int idx=oldFilename.lastIndexOf(".");
String extention=oldFilename.substring(idx);
//取文件名
String newFilename=oldFilename.substring(0,idx);
//得到不重复的文件名,用iidd加文件名
String sServerFileName = (String)filenametemp.toString();
sServerFileName =sServerFileName+newFilename+extention;
File sServerFile= new File(saveDirectory+"\\" + sServerFileName);
f.renameTo(sServerFile);
String FileName = sServerFile.getName();
//放在上两级目录下(根目录的文件夹下)
//String comparafileName = "../../" + folderName + "/" + FileName;
comparafileName = relativePath + folderName + "/" + FileName;
System.out.print("文件的相对路径:"+comparafileName);
fileURL = realURL + "/" + folderName + "/" + FileName;
}
}
sb.append("<html><body>");
sb.append("<input id = \"UploadIsSucces\" type=\"hidden\" value=\"1\" />");
sb.append("图片已经上传成功!");
sb.append("<br /> 图片描述:");
sb.append(fileDesName);
sb.append("<br />图片url:");
sb.append(fileURL);
String img = "<br /><img src='" + fileURL + "' />";
sb.append(img);
sb.append("</body></html>");
result = sb.toString();
//System.out.println(rs);
}
catch(Exception e)
{
System.out.println("message=" + e.getMessage());
//Posted content length of 42654262 exceeds limit of 10485760
String message = e.getMessage();
if(message.indexOf("Posted content length of") !=-1)
{
String content = message.split("length of ")[1].split(" exceeds")[0];
int ct = Integer.parseInt(content);
String limit = message.split("limit of ")[1];
int lt = Integer.parseInt(limit);
result = "对不起,你上传的图片大小为" + ct/(1024*1024) + "MB,超过了最大限制" + lt/(1024*1024) + "MB" ;
}
else
{
result = "上传失败";
}
e.printStackTrace();
}
try
{
xmlout.write(result);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
xmlout.flush();
xmlout.close();
}
%>
下载地址 http://www.servlets.com/cos/index.html
下载链接 http://www.servlets.com/cos/cos-26Dec2008.zip
upload.html
<html>
<head>
<title>upload</title>
<script type="text/javascript" src="./javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="./javascript/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('ok');
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>
<body scroll="no">
<center>
<form id="uploadimage" name="uploadimage" method="post"
action="./upload.jsp?folderName=uploadImage&relativePath=../../"
>
<table width=600 border=0 align="center" cellPadding=0 cellSpacing=0
id="table1" frame="void" style="BORDER-LEFT: #ffffff 0px solid;">
<input type=hidden id="UploadIsSucces" value="0" />
<tr bgcolor="#FFFFFF">
<td width="100" align="center">
选择图片
</td>
<td width="490" colspan="3" rowspan="2">
<input type="file" name="upimage" id="upimage" size="30">
<input type="text" name="imgdes" id="imgdes" size="40">
</td>
</tr>
<tr bgcolor="#FFFFFF">
<td align="center">
图片描述
</td>
</tr>
<tr>
<td>
<input type="submit" id="sub" value="submit" />
<br />
<a href="#" id="testJS">testJS</a>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
-----------------------------------------------华丽分割线--------------------------------------------------------------------
upload.jsp
<%@ page contentType="text/html; charset=gbk" language="java" errorPage="" %>
<%@ page language="java" import="java.io.PrintWriter"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.util.UUID"%>
<%@ page language="java" import="java.util.Enumeration"%>
<%@ page language="java" import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.FileRenamePolicy"%>
<%
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("gbk");
PrintWriter xmlout = response.getWriter();
String uuid = UUID.randomUUID().toString();
//文件的fileURL
String fileURL = "";
// 上传文件名
String fileName = null;
//取得文件描述
String fileDesName = "";
StringBuffer sb = new StringBuffer();
String result = "";
try
{
//得到此源文件的目录
String realPath = getServletContext().getRealPath("");
String contentPath = request.getContextPath();
String requestURL = request.getRequestURL().toString();
String realURL = requestURL.split(contentPath)[0] + contentPath;
//上传文件存放的文件夹名称,一律放在根目录下的文件夹里面即folderName/
String folderName = request.getParameter("folderName");
//根据不同层级../../的路径不同
String relativePath = request.getParameter("relativePath");
//文件的相对路径
String comparafileName = "";
// 将上传文件存放在saveDirectory
String saveDirectory = realPath + "/" + folderName;
System.out.println("saveDirectory= " + saveDirectory);
File uploadPath = new File(saveDirectory);
if (!uploadPath.exists())
{
uploadPath.mkdir();
}
// 上传文件的大小限制在10 MB
int maxPostSize = 10 * 1024 * 1024;
//实现将上传文件更名,以防同名覆盖和同时上传两个文件名相同的文件,自动在文件名后面加1(在1~9999范围内)
FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();
// 上传文件
MultipartRequest multi = new MultipartRequest(request,saveDirectory, maxPostSize, "GBK",policy);
StringBuffer filenametemp = new StringBuffer();
filenametemp.append(uuid);
//在iidd后面加一下划线"-"以便和文件名称区分出来
filenametemp.append("-");
//取得文件描述
fileDesName = multi.getParameter("imgdes");
//System.out.println("文件描述:"+ fileDesName);
// 取得所有上传文件名称
Enumeration filesname = multi.getFileNames();
while (filesname.hasMoreElements())
{
String name = (String) filesname.nextElement();
//文件上传的完整路径
File f = multi.getFile(name);
//文件名称
fileName = multi.getFilesystemName(name);
if (fileName != null)
{
String oldFilename=fileName;
int idx=oldFilename.lastIndexOf(".");
String extention=oldFilename.substring(idx);
//取文件名
String newFilename=oldFilename.substring(0,idx);
//得到不重复的文件名,用iidd加文件名
String sServerFileName = (String)filenametemp.toString();
sServerFileName =sServerFileName+newFilename+extention;
File sServerFile= new File(saveDirectory+"\\" + sServerFileName);
f.renameTo(sServerFile);
String FileName = sServerFile.getName();
//放在上两级目录下(根目录的文件夹下)
//String comparafileName = "../../" + folderName + "/" + FileName;
comparafileName = relativePath + folderName + "/" + FileName;
System.out.print("文件的相对路径:"+comparafileName);
fileURL = realURL + "/" + folderName + "/" + FileName;
}
}
sb.append("<html><body>");
sb.append("<input id = \"UploadIsSucces\" type=\"hidden\" value=\"1\" />");
sb.append("图片已经上传成功!");
sb.append("<br /> 图片描述:");
sb.append(fileDesName);
sb.append("<br />图片url:");
sb.append(fileURL);
String img = "<br /><img src='" + fileURL + "' />";
sb.append(img);
sb.append("</body></html>");
result = sb.toString();
//System.out.println(rs);
}
catch(Exception e)
{
System.out.println("message=" + e.getMessage());
//Posted content length of 42654262 exceeds limit of 10485760
String message = e.getMessage();
if(message.indexOf("Posted content length of") !=-1)
{
String content = message.split("length of ")[1].split(" exceeds")[0];
int ct = Integer.parseInt(content);
String limit = message.split("limit of ")[1];
int lt = Integer.parseInt(limit);
result = "对不起,你上传的图片大小为" + ct/(1024*1024) + "MB,超过了最大限制" + lt/(1024*1024) + "MB" ;
}
else
{
result = "上传失败";
}
e.printStackTrace();
}
try
{
xmlout.write(result);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
xmlout.flush();
xmlout.close();
}
%>
#13
谢谢大家,我用struts1.2.8解决了。
以下是我的方法:
这是action:
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
以下是我的方法:
这是action:
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
#14
楼主好人,呵呵,问题解决请及时结帖
#15
你能不能写的详细点了,有的不是太清楚,我是小菜鸟,你干脆写完整吧
#16
请大纳们给讲解用SSH框架开发通过common-fileupload来实现上传下载,谢谢了,如果没有时间,有没有现成的代码了,我自己看就行了,谢谢了!!
#17
这是action:
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
我用这方法怎么不行呢,我只会jsp上传图片,请大家来解决一下,谢谢
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
我用这方法怎么不行呢,我只会jsp上传图片,请大家来解决一下,谢谢
#18
我的页面是这样的
<form action="upLoad.do" name="formFile">
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" >
<input type="submit" value="上传">
</form>
报错
class FileUpLoadForm
=======null
2010-2-2 20:24:48 org.apache.struts.action.RequestProcessor processException
警告: Unhandled Exception thrown: class java.lang.NullPointerException
2010-2-2 20:24:48 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet action threw exception
java.lang.NullPointerException
at FileUpLoadAction.doUpLoadImg(FileUpLoadAction.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
能告诉我页面代码是样的吗?
<form action="upLoad.do" name="formFile">
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" >
<input type="submit" value="上传">
</form>
报错
class FileUpLoadForm
=======null
2010-2-2 20:24:48 org.apache.struts.action.RequestProcessor processException
警告: Unhandled Exception thrown: class java.lang.NullPointerException
2010-2-2 20:24:48 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet action threw exception
java.lang.NullPointerException
at FileUpLoadAction.doUpLoadImg(FileUpLoadAction.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
能告诉我页面代码是样的吗?
#19
<form action="upLoad.do" method ="POST" enctype ="multipart/form-data" >
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" name="formFile" >
<input type="submit" value="上传">
</form>
我解决了,但是搞不懂 enctype ="multipart/form-data" 是什么?
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" name="formFile" >
<input type="submit" value="上传">
</form>
我解决了,但是搞不懂 enctype ="multipart/form-data" 是什么?
#20
哥们,这句得到什么啊String contentType = myFile.getContentType();麻烦指教
#21
package com.huchuhan.img_upload.action;
import java.io.File;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadsAction extends ActionSupport {
private static final long serialVersionUID = 1157141200452916950L;
private File[] file;
private String[] fileFileName;
private String[] fileContentType;
private String[] fileName;
public String uploads() throws Exception {
if (file != null && file.length > 0) {
fileName=new String[file.length];
for (int i = 0; i < file.length; i++) {
// 利用时间戳生成不会重复的文件名
fileName[i] = new Date().getTime()
+this.getExtention(fileFileName[i]);
System.out.println(fileName[i]);
// 设置文件在服务器上的存储路径, 以便读取
File newFile = new File(ServletActionContext
.getServletContext().getRealPath(
File.separator + "UploadImages"
+ File.separator + fileName[i]));
System.out.println(newFile.getAbsolutePath());
// 直接使用struts2提供的文件操作工具类, 将要上传的文件存储到服务器
FileUtils.copyFile(file[i], newFile);
}
}else
{
System.out.println("没有文件");
return INPUT;
}
return SUCCESS;
}
// 获得文件扩展名
private String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
public File[] getFile() {
return file;
}
public void setFile(File[] file) {
this.file = file;
}
public String[] getFileFileName() {
return fileFileName;
}
public void setFileFileName(String[] fileFileName) {
this.fileFileName = fileFileName;
}
public String[] getFileContentType() {
return fileContentType;
}
public void setFileContentType(String[] fileContentType) {
this.fileContentType = fileContentType;
}
public void setFileName(String[] fileName) {
this.fileName = fileName;
}
public String[] getFileName() {
return fileName;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.multipart.saveDir" value="C:\"></constant>
<package name="struts2" extends="struts-default">
<action name="uploads" class="com.huchuhan.img_upload.action.UploadsAction" method="uploads">
<result name="success">/jsp/shows.jsp</result>
<result name="input" type="redirect">/jsp/uploads.jsp</result>
</action>
</package>
</struts>
uploads.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/jsp/share/taglib.jsp" %>
<!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>Uploads</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
var i=1;
function addMore()
{
$("#submit").css("display","inline");
var addButton=document.getElementById("add");
addButton.value="add more...";
var table=document.getElementById("table");
if(table.childNodes.length==1)
{
$("#del").css("display", "inline");
}
var tr=document.createElement("tr");
var td1=document.createElement("td");
var td2=document.createElement("td");
var td3=document.createElement("td");
var file=document.createElement("input");
var button=document.createElement("input");
file.type="file";
file.name="file";
button.type="button";
button.value="remove";
button.onclick=function()
{
if(table.childNodes.length==1)
{
addButton.value="add";
$("#del").css("display", "none");
$("#submit").css("display","none");
}
table.removeChild(tr);
};
td1.innerHTML="file"+i;
td1.align="center";
td2.appendChild(file);
td3.appendChild(button);
td3.align="center";
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
table.appendChild(tr);
i++;
}
function delAll(o)
{
var table=document.getElementById("table");
//在ie下,对于COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR,innerHTML属性是只读的。
//也就是说你不能通过innerhtml对这些标签进行操作。
//table.innerHTML=""; //ie 不支持, 用以下代码代替.
var childs=table.childNodes;
var length=childs.length;
for(var i=0;i<length;i++)
{
table.removeChild(childs[0]);
}
var addButton=document.getElementById("add");
addButton.value="add";
$("#submit").css("display","none");
$(o).css("display", "none");
}
</script>
</head>
<body>
<s:form action="uploads" method="post" enctype="multipart/form-data" theme="simple">
<table border="0">
<tr>
<td align="center">
<input id="add" type="button" value="add" onclick="addMore()"/>
</td>
<td align="center">
<input id="del" type="button" value="delAll" onclick="delAll(this)" style="display:none; "/>
</td>
</tr>
</table>
<table id="table" border="0"></table>
<input type="submit" id="submit" value="submit" style="display: none;"/>
</s:form>
</body>
</html>
shows.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/share/taglib.jsp" %>
<!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>show img</title>
</head>
<body>
<c:forEach items="${fileName}" var="v">
<div style="padding: 3px; border: solid 1px #cccccc; text-align:center">
<img src ="../UploadImages/${v}"/>
<br/>
</div>
</c:forEach>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Img-Upload</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 引入struts2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
#22
#23
#24
学习了!!太谢谢了!!!
#25
#1
感覺你已經說的很詳細了,LZ不是有思路了嗎?
#2
用struts的标签实现,具体你google一下。
#3
我是想到这个大概思路的,但是具体怎么实现还是很模糊!我上了google搜一下,有用common-fileupload实现的 但是很多地方不清楚。能具体一点就好了。
#4
类中要有这三个属性
private File upload;
private String uploadContentType;
private String uploadFileName;
页面
<input name="upload" type="file" class="input_style2" id="upload" size="30" />
处理逻辑:
File picFile = new File(this.getRealPath() + "/**");
if (!picFile.exists()) {
picFile.mkdirs();
}
String fileReName = this.getUploadFileName() + "." + getUploadSuffix(类的实例.getUploadFileName());
类的实例.getUpload().renameTo(new File(picFile.getPath(), fileReName));
private File upload;
private String uploadContentType;
private String uploadFileName;
页面
<input name="upload" type="file" class="input_style2" id="upload" size="30" />
处理逻辑:
File picFile = new File(this.getRealPath() + "/**");
if (!picFile.exists()) {
picFile.mkdirs();
}
String fileReName = this.getUploadFileName() + "." + getUploadSuffix(类的实例.getUploadFileName());
类的实例.getUpload().renameTo(new File(picFile.getPath(), fileReName));
#5
public static String upload(String path, FormFile formFile, String filename) throws Exception {
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
// 取欲上传的文件的名字和长度
String fname = formFile.getFileName();
String randomStr = Integer.toString((int)(Math.random()*1000));
// 将上传时间加入文件名
int i = fname.indexOf(".");
//String name = String.valueOf(date.getTime());
String name = format.format(date);
String type = fname.substring(i + 1);
if(filename == null || filename.equals("")){
fname = name +"_"+randomStr+ "." + type;
}else{
fname = name +"_"+randomStr +"_" + filename + "." + type;
}
InputStream streamIn = formFile.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
if (!uploadFile.exists() || uploadFile == null) { // 判断指定路径是否存在,不存在则创建路径
uploadFile.mkdirs();
}
String path = uploadFile.getPath() + "\\" + fname;
//System.out.println("内 :"+path);
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.flush();
streamOut.close();
streamIn.close();
formFile.destroy();
return fname;
}
SimpleDateFormat format=new SimpleDateFormat("yyyyMMddHHmmss");
Date date = new Date();
// 取欲上传的文件的名字和长度
String fname = formFile.getFileName();
String randomStr = Integer.toString((int)(Math.random()*1000));
// 将上传时间加入文件名
int i = fname.indexOf(".");
//String name = String.valueOf(date.getTime());
String name = format.format(date);
String type = fname.substring(i + 1);
if(filename == null || filename.equals("")){
fname = name +"_"+randomStr+ "." + type;
}else{
fname = name +"_"+randomStr +"_" + filename + "." + type;
}
InputStream streamIn = formFile.getInputStream(); // 创建读取用户上传文件的对象
File uploadFile = new File(dir); // 创建把上传数据写到目标文件的对象
if (!uploadFile.exists() || uploadFile == null) { // 判断指定路径是否存在,不存在则创建路径
uploadFile.mkdirs();
}
String path = uploadFile.getPath() + "\\" + fname;
//System.out.println("内 :"+path);
OutputStream streamOut = new FileOutputStream(path);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
streamOut.write(buffer, 0, bytesRead);
}
streamOut.flush();
streamOut.close();
streamIn.close();
formFile.destroy();
return fname;
}
#6
学习了。。。
#7
struts2 有专门的上传文件的
#8
你这个把图片的本地路径保存在数据库,显示的时候赋给img的src属性是不可行的!
客户端在不同机器,你能保证他e盘下都有那张图片?感觉lz的思路有偏差!
图片路径你得采用图片保存在服务器上的路径,相对绝对随你,至于图片怎么上传的,网上资料很多
客户端在不同机器,你能保证他e盘下都有那张图片?感觉lz的思路有偏差!
图片路径你得采用图片保存在服务器上的路径,相对绝对随你,至于图片怎么上传的,网上资料很多
#9
LZ 去看看把
http://www.javaeye.com/wiki/Struts2_leader_guide/1986-struts_guide_10
http://www.javaeye.com/wiki/Struts2_leader_guide/1986-struts_guide_10
#10
if (null != this.getPhotoFile()) {
// 从画面上取得图片文件
File files = this.getPhotoFile();
// 文件名 = 文件名 + 日期
photoFileFileName = new Date().getTime() + photoFileFileName.trim();
String path = ServletActionContext.getServletContext().getRealPath("/");
if (!path.endsWith("\\")) {
path = path + "\\";
}
String savePath = path + "\\UploadImages\\";
// 判断保存用文件夹是否存在
mkdir(savePath);
// 保存用的数据流生成
FileOutputStream fos = null;
FileInputStream fis = null;
try {
// 保存用的数据流生成
fos = new FileOutputStream(savePath + photoFileFileName);
System.out.println(savePath + photoFileFileName);
// 保存文件
fis = new FileInputStream(files);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
cond.setPhotoPath(savePath+photoFileFileName);
} catch (FileNotFoundException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}
}
}else{
cond.setPhotoPath(null);
}
// 从画面上取得图片文件
File files = this.getPhotoFile();
// 文件名 = 文件名 + 日期
photoFileFileName = new Date().getTime() + photoFileFileName.trim();
String path = ServletActionContext.getServletContext().getRealPath("/");
if (!path.endsWith("\\")) {
path = path + "\\";
}
String savePath = path + "\\UploadImages\\";
// 判断保存用文件夹是否存在
mkdir(savePath);
// 保存用的数据流生成
FileOutputStream fos = null;
FileInputStream fis = null;
try {
// 保存用的数据流生成
fos = new FileOutputStream(savePath + photoFileFileName);
System.out.println(savePath + photoFileFileName);
// 保存文件
fis = new FileInputStream(files);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
cond.setPhotoPath(savePath+photoFileFileName);
} catch (FileNotFoundException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}finally {
try {
fos.close();
fis.close();
} catch (IOException e) {
addActionError("照片上传失败!");
cond.setPhotoPath(null);
}
}
}else{
cond.setPhotoPath(null);
}
#11
#12
用cos上传组件
下载地址 http://www.servlets.com/cos/index.html
下载链接 http://www.servlets.com/cos/cos-26Dec2008.zip
upload.html
<html>
<head>
<title>upload</title>
<script type="text/javascript" src="./javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="./javascript/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('ok');
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>
<body scroll="no">
<center>
<form id="uploadimage" name="uploadimage" method="post"
action="./upload.jsp?folderName=uploadImage&relativePath=../../"
>
<table width=600 border=0 align="center" cellPadding=0 cellSpacing=0
id="table1" frame="void" style="BORDER-LEFT: #ffffff 0px solid;">
<input type=hidden id="UploadIsSucces" value="0" />
<tr bgcolor="#FFFFFF">
<td width="100" align="center">
选择图片
</td>
<td width="490" colspan="3" rowspan="2">
<input type="file" name="upimage" id="upimage" size="30">
<input type="text" name="imgdes" id="imgdes" size="40">
</td>
</tr>
<tr bgcolor="#FFFFFF">
<td align="center">
图片描述
</td>
</tr>
<tr>
<td>
<input type="submit" id="sub" value="submit" />
<br />
<a href="#" id="testJS">testJS</a>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
-----------------------------------------------华丽分割线--------------------------------------------------------------------
upload.jsp
<%@ page contentType="text/html; charset=gbk" language="java" errorPage="" %>
<%@ page language="java" import="java.io.PrintWriter"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.util.UUID"%>
<%@ page language="java" import="java.util.Enumeration"%>
<%@ page language="java" import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.FileRenamePolicy"%>
<%
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("gbk");
PrintWriter xmlout = response.getWriter();
String uuid = UUID.randomUUID().toString();
//文件的fileURL
String fileURL = "";
// 上传文件名
String fileName = null;
//取得文件描述
String fileDesName = "";
StringBuffer sb = new StringBuffer();
String result = "";
try
{
//得到此源文件的目录
String realPath = getServletContext().getRealPath("");
String contentPath = request.getContextPath();
String requestURL = request.getRequestURL().toString();
String realURL = requestURL.split(contentPath)[0] + contentPath;
//上传文件存放的文件夹名称,一律放在根目录下的文件夹里面即folderName/
String folderName = request.getParameter("folderName");
//根据不同层级../../的路径不同
String relativePath = request.getParameter("relativePath");
//文件的相对路径
String comparafileName = "";
// 将上传文件存放在saveDirectory
String saveDirectory = realPath + "/" + folderName;
System.out.println("saveDirectory= " + saveDirectory);
File uploadPath = new File(saveDirectory);
if (!uploadPath.exists())
{
uploadPath.mkdir();
}
// 上传文件的大小限制在10 MB
int maxPostSize = 10 * 1024 * 1024;
//实现将上传文件更名,以防同名覆盖和同时上传两个文件名相同的文件,自动在文件名后面加1(在1~9999范围内)
FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();
// 上传文件
MultipartRequest multi = new MultipartRequest(request,saveDirectory, maxPostSize, "GBK",policy);
StringBuffer filenametemp = new StringBuffer();
filenametemp.append(uuid);
//在iidd后面加一下划线"-"以便和文件名称区分出来
filenametemp.append("-");
//取得文件描述
fileDesName = multi.getParameter("imgdes");
//System.out.println("文件描述:"+ fileDesName);
// 取得所有上传文件名称
Enumeration filesname = multi.getFileNames();
while (filesname.hasMoreElements())
{
String name = (String) filesname.nextElement();
//文件上传的完整路径
File f = multi.getFile(name);
//文件名称
fileName = multi.getFilesystemName(name);
if (fileName != null)
{
String oldFilename=fileName;
int idx=oldFilename.lastIndexOf(".");
String extention=oldFilename.substring(idx);
//取文件名
String newFilename=oldFilename.substring(0,idx);
//得到不重复的文件名,用iidd加文件名
String sServerFileName = (String)filenametemp.toString();
sServerFileName =sServerFileName+newFilename+extention;
File sServerFile= new File(saveDirectory+"\\" + sServerFileName);
f.renameTo(sServerFile);
String FileName = sServerFile.getName();
//放在上两级目录下(根目录的文件夹下)
//String comparafileName = "../../" + folderName + "/" + FileName;
comparafileName = relativePath + folderName + "/" + FileName;
System.out.print("文件的相对路径:"+comparafileName);
fileURL = realURL + "/" + folderName + "/" + FileName;
}
}
sb.append("<html><body>");
sb.append("<input id = \"UploadIsSucces\" type=\"hidden\" value=\"1\" />");
sb.append("图片已经上传成功!");
sb.append("<br /> 图片描述:");
sb.append(fileDesName);
sb.append("<br />图片url:");
sb.append(fileURL);
String img = "<br /><img src='" + fileURL + "' />";
sb.append(img);
sb.append("</body></html>");
result = sb.toString();
//System.out.println(rs);
}
catch(Exception e)
{
System.out.println("message=" + e.getMessage());
//Posted content length of 42654262 exceeds limit of 10485760
String message = e.getMessage();
if(message.indexOf("Posted content length of") !=-1)
{
String content = message.split("length of ")[1].split(" exceeds")[0];
int ct = Integer.parseInt(content);
String limit = message.split("limit of ")[1];
int lt = Integer.parseInt(limit);
result = "对不起,你上传的图片大小为" + ct/(1024*1024) + "MB,超过了最大限制" + lt/(1024*1024) + "MB" ;
}
else
{
result = "上传失败";
}
e.printStackTrace();
}
try
{
xmlout.write(result);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
xmlout.flush();
xmlout.close();
}
%>
下载地址 http://www.servlets.com/cos/index.html
下载链接 http://www.servlets.com/cos/cos-26Dec2008.zip
upload.html
<html>
<head>
<title>upload</title>
<script type="text/javascript" src="./javascript/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="./javascript/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
alert('ok');
});
</script>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>
<body scroll="no">
<center>
<form id="uploadimage" name="uploadimage" method="post"
action="./upload.jsp?folderName=uploadImage&relativePath=../../"
>
<table width=600 border=0 align="center" cellPadding=0 cellSpacing=0
id="table1" frame="void" style="BORDER-LEFT: #ffffff 0px solid;">
<input type=hidden id="UploadIsSucces" value="0" />
<tr bgcolor="#FFFFFF">
<td width="100" align="center">
选择图片
</td>
<td width="490" colspan="3" rowspan="2">
<input type="file" name="upimage" id="upimage" size="30">
<input type="text" name="imgdes" id="imgdes" size="40">
</td>
</tr>
<tr bgcolor="#FFFFFF">
<td align="center">
图片描述
</td>
</tr>
<tr>
<td>
<input type="submit" id="sub" value="submit" />
<br />
<a href="#" id="testJS">testJS</a>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
-----------------------------------------------华丽分割线--------------------------------------------------------------------
upload.jsp
<%@ page contentType="text/html; charset=gbk" language="java" errorPage="" %>
<%@ page language="java" import="java.io.PrintWriter"%>
<%@ page language="java" import="java.io.*"%>
<%@ page language="java" import="java.util.UUID"%>
<%@ page language="java" import="java.util.Enumeration"%>
<%@ page language="java" import="com.oreilly.servlet.MultipartRequest"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@ page language="java" import="com.oreilly.servlet.multipart.FileRenamePolicy"%>
<%
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("gbk");
PrintWriter xmlout = response.getWriter();
String uuid = UUID.randomUUID().toString();
//文件的fileURL
String fileURL = "";
// 上传文件名
String fileName = null;
//取得文件描述
String fileDesName = "";
StringBuffer sb = new StringBuffer();
String result = "";
try
{
//得到此源文件的目录
String realPath = getServletContext().getRealPath("");
String contentPath = request.getContextPath();
String requestURL = request.getRequestURL().toString();
String realURL = requestURL.split(contentPath)[0] + contentPath;
//上传文件存放的文件夹名称,一律放在根目录下的文件夹里面即folderName/
String folderName = request.getParameter("folderName");
//根据不同层级../../的路径不同
String relativePath = request.getParameter("relativePath");
//文件的相对路径
String comparafileName = "";
// 将上传文件存放在saveDirectory
String saveDirectory = realPath + "/" + folderName;
System.out.println("saveDirectory= " + saveDirectory);
File uploadPath = new File(saveDirectory);
if (!uploadPath.exists())
{
uploadPath.mkdir();
}
// 上传文件的大小限制在10 MB
int maxPostSize = 10 * 1024 * 1024;
//实现将上传文件更名,以防同名覆盖和同时上传两个文件名相同的文件,自动在文件名后面加1(在1~9999范围内)
FileRenamePolicy policy =(FileRenamePolicy)new DefaultFileRenamePolicy();
// 上传文件
MultipartRequest multi = new MultipartRequest(request,saveDirectory, maxPostSize, "GBK",policy);
StringBuffer filenametemp = new StringBuffer();
filenametemp.append(uuid);
//在iidd后面加一下划线"-"以便和文件名称区分出来
filenametemp.append("-");
//取得文件描述
fileDesName = multi.getParameter("imgdes");
//System.out.println("文件描述:"+ fileDesName);
// 取得所有上传文件名称
Enumeration filesname = multi.getFileNames();
while (filesname.hasMoreElements())
{
String name = (String) filesname.nextElement();
//文件上传的完整路径
File f = multi.getFile(name);
//文件名称
fileName = multi.getFilesystemName(name);
if (fileName != null)
{
String oldFilename=fileName;
int idx=oldFilename.lastIndexOf(".");
String extention=oldFilename.substring(idx);
//取文件名
String newFilename=oldFilename.substring(0,idx);
//得到不重复的文件名,用iidd加文件名
String sServerFileName = (String)filenametemp.toString();
sServerFileName =sServerFileName+newFilename+extention;
File sServerFile= new File(saveDirectory+"\\" + sServerFileName);
f.renameTo(sServerFile);
String FileName = sServerFile.getName();
//放在上两级目录下(根目录的文件夹下)
//String comparafileName = "../../" + folderName + "/" + FileName;
comparafileName = relativePath + folderName + "/" + FileName;
System.out.print("文件的相对路径:"+comparafileName);
fileURL = realURL + "/" + folderName + "/" + FileName;
}
}
sb.append("<html><body>");
sb.append("<input id = \"UploadIsSucces\" type=\"hidden\" value=\"1\" />");
sb.append("图片已经上传成功!");
sb.append("<br /> 图片描述:");
sb.append(fileDesName);
sb.append("<br />图片url:");
sb.append(fileURL);
String img = "<br /><img src='" + fileURL + "' />";
sb.append(img);
sb.append("</body></html>");
result = sb.toString();
//System.out.println(rs);
}
catch(Exception e)
{
System.out.println("message=" + e.getMessage());
//Posted content length of 42654262 exceeds limit of 10485760
String message = e.getMessage();
if(message.indexOf("Posted content length of") !=-1)
{
String content = message.split("length of ")[1].split(" exceeds")[0];
int ct = Integer.parseInt(content);
String limit = message.split("limit of ")[1];
int lt = Integer.parseInt(limit);
result = "对不起,你上传的图片大小为" + ct/(1024*1024) + "MB,超过了最大限制" + lt/(1024*1024) + "MB" ;
}
else
{
result = "上传失败";
}
e.printStackTrace();
}
try
{
xmlout.write(result);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
xmlout.flush();
xmlout.close();
}
%>
#13
谢谢大家,我用struts1.2.8解决了。
以下是我的方法:
这是action:
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
以下是我的方法:
这是action:
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
#14
楼主好人,呵呵,问题解决请及时结帖
#15
你能不能写的详细点了,有的不是太清楚,我是小菜鸟,你干脆写完整吧
#16
请大纳们给讲解用SSH框架开发通过common-fileupload来实现上传下载,谢谢了,如果没有时间,有没有现成的代码了,我自己看就行了,谢谢了!!
#17
这是action:
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
我用这方法怎么不行呢,我只会jsp上传图片,请大家来解决一下,谢谢
FileUpLoadForm fileUpLoadForm = (FileUpLoadForm) form;
System.out.println(fileUpLoadForm.getClass());
FormFile myFile = fileUpLoadForm.getFormFile();
System.out.println("=======" + myFile);
String contentType = myFile.getContentType();
System.out.println(contentType);
String fileName = myFile.getFileName();
System.out.println(fileName);
try {
String filePath = getServlet().getServletContext().getRealPath("/")
+ "images";
System.out.println(getServlet());
if (!fileName.equals("")) {
System.out.println(filePath);
File fileToCreate = new File(filePath, fileName);
if (!fileToCreate.exists()) {
FileOutputStream fileOutStream = new FileOutputStream(
fileToCreate);
fileOutStream.write(myFile.getFileData());
fileOutStream.flush();
fileOutStream.close();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
这是Form:
private FormFile formFile;
public ActionErrors validate(ActionMapping mapping,
HttpServletRequest request) {
return null;
}
/**
* Method reset
* @param mapping
* @param request
*/
public void reset(ActionMapping mapping, HttpServletRequest request) {
}
public FormFile getFormFile() {
return formFile;
}
public void setFormFile(FormFile formFile) {
this.formFile = formFile;
}
希望着对遇到同样问题的人能有帮助。。。
使用这种方法是struts帮我们做太多事情了。。。。。
我用这方法怎么不行呢,我只会jsp上传图片,请大家来解决一下,谢谢
#18
我的页面是这样的
<form action="upLoad.do" name="formFile">
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" >
<input type="submit" value="上传">
</form>
报错
class FileUpLoadForm
=======null
2010-2-2 20:24:48 org.apache.struts.action.RequestProcessor processException
警告: Unhandled Exception thrown: class java.lang.NullPointerException
2010-2-2 20:24:48 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet action threw exception
java.lang.NullPointerException
at FileUpLoadAction.doUpLoadImg(FileUpLoadAction.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
能告诉我页面代码是样的吗?
<form action="upLoad.do" name="formFile">
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" >
<input type="submit" value="上传">
</form>
报错
class FileUpLoadForm
=======null
2010-2-2 20:24:48 org.apache.struts.action.RequestProcessor processException
警告: Unhandled Exception thrown: class java.lang.NullPointerException
2010-2-2 20:24:48 org.apache.catalina.core.StandardWrapperValve invoke
严重: Servlet.service() for servlet action threw exception
java.lang.NullPointerException
at FileUpLoadAction.doUpLoadImg(FileUpLoadAction.java:25)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:690)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:128)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:263)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:584)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:447)
at java.lang.Thread.run(Unknown Source)
能告诉我页面代码是样的吗?
#19
<form action="upLoad.do" method ="POST" enctype ="multipart/form-data" >
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" name="formFile" >
<input type="submit" value="上传">
</form>
我解决了,但是搞不懂 enctype ="multipart/form-data" 是什么?
<input type="hidden" value="doUpLoadImg" name="op">
<input type="file" name="formFile" >
<input type="submit" value="上传">
</form>
我解决了,但是搞不懂 enctype ="multipart/form-data" 是什么?
#20
哥们,这句得到什么啊String contentType = myFile.getContentType();麻烦指教
#21
package com.huchuhan.img_upload.action;
import java.io.File;
import java.util.Date;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class UploadsAction extends ActionSupport {
private static final long serialVersionUID = 1157141200452916950L;
private File[] file;
private String[] fileFileName;
private String[] fileContentType;
private String[] fileName;
public String uploads() throws Exception {
if (file != null && file.length > 0) {
fileName=new String[file.length];
for (int i = 0; i < file.length; i++) {
// 利用时间戳生成不会重复的文件名
fileName[i] = new Date().getTime()
+this.getExtention(fileFileName[i]);
System.out.println(fileName[i]);
// 设置文件在服务器上的存储路径, 以便读取
File newFile = new File(ServletActionContext
.getServletContext().getRealPath(
File.separator + "UploadImages"
+ File.separator + fileName[i]));
System.out.println(newFile.getAbsolutePath());
// 直接使用struts2提供的文件操作工具类, 将要上传的文件存储到服务器
FileUtils.copyFile(file[i], newFile);
}
}else
{
System.out.println("没有文件");
return INPUT;
}
return SUCCESS;
}
// 获得文件扩展名
private String getExtention(String fileName) {
int pos = fileName.lastIndexOf(".");
return fileName.substring(pos);
}
public File[] getFile() {
return file;
}
public void setFile(File[] file) {
this.file = file;
}
public String[] getFileFileName() {
return fileFileName;
}
public void setFileFileName(String[] fileFileName) {
this.fileFileName = fileFileName;
}
public String[] getFileContentType() {
return fileContentType;
}
public void setFileContentType(String[] fileContentType) {
this.fileContentType = fileContentType;
}
public void setFileName(String[] fileName) {
this.fileName = fileName;
}
public String[] getFileName() {
return fileName;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.multipart.saveDir" value="C:\"></constant>
<package name="struts2" extends="struts-default">
<action name="uploads" class="com.huchuhan.img_upload.action.UploadsAction" method="uploads">
<result name="success">/jsp/shows.jsp</result>
<result name="input" type="redirect">/jsp/uploads.jsp</result>
</action>
</package>
</struts>
uploads.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ include file="/jsp/share/taglib.jsp" %>
<!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>Uploads</title>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
var i=1;
function addMore()
{
$("#submit").css("display","inline");
var addButton=document.getElementById("add");
addButton.value="add more...";
var table=document.getElementById("table");
if(table.childNodes.length==1)
{
$("#del").css("display", "inline");
}
var tr=document.createElement("tr");
var td1=document.createElement("td");
var td2=document.createElement("td");
var td3=document.createElement("td");
var file=document.createElement("input");
var button=document.createElement("input");
file.type="file";
file.name="file";
button.type="button";
button.value="remove";
button.onclick=function()
{
if(table.childNodes.length==1)
{
addButton.value="add";
$("#del").css("display", "none");
$("#submit").css("display","none");
}
table.removeChild(tr);
};
td1.innerHTML="file"+i;
td1.align="center";
td2.appendChild(file);
td3.appendChild(button);
td3.align="center";
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
table.appendChild(tr);
i++;
}
function delAll(o)
{
var table=document.getElementById("table");
//在ie下,对于COL, COLGROUP, FRAMESET, HTML, STYLE, TABLE, TBODY, TFOOT, THEAD, TITLE, TR,innerHTML属性是只读的。
//也就是说你不能通过innerhtml对这些标签进行操作。
//table.innerHTML=""; //ie 不支持, 用以下代码代替.
var childs=table.childNodes;
var length=childs.length;
for(var i=0;i<length;i++)
{
table.removeChild(childs[0]);
}
var addButton=document.getElementById("add");
addButton.value="add";
$("#submit").css("display","none");
$(o).css("display", "none");
}
</script>
</head>
<body>
<s:form action="uploads" method="post" enctype="multipart/form-data" theme="simple">
<table border="0">
<tr>
<td align="center">
<input id="add" type="button" value="add" onclick="addMore()"/>
</td>
<td align="center">
<input id="del" type="button" value="delAll" onclick="delAll(this)" style="display:none; "/>
</td>
</tr>
</table>
<table id="table" border="0"></table>
<input type="submit" id="submit" value="submit" style="display: none;"/>
</s:form>
</body>
</html>
shows.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@include file="/jsp/share/taglib.jsp" %>
<!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>show img</title>
</head>
<body>
<c:forEach items="${fileName}" var="v">
<div style="padding: 3px; border: solid 1px #cccccc; text-align:center">
<img src ="../UploadImages/${v}"/>
<br/>
</div>
</c:forEach>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>Img-Upload</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 引入struts2 -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
#22
#23
#24
学习了!!太谢谢了!!!