当前位置:首页 » 文件管理 » struts2action文件上传

struts2action文件上传

发布时间: 2022-05-27 11:52:16

❶ struts2文件上传和下载

1,上传方法
(1),页面form表单添加一个属性为enctype="multipart/form-data" 和method="post"

(2),假设上传预览框为 <input type="file" name="myfile" />
(3),控制器接值的方法为
private File myfile; //要上传的文件

private String myfileFileName; //要上传文件名称
private String myfileContentType; //要上传文件类型
别忘了做set方法

(4), 接到值后可以保存到数据库,也可以保存到硬盘,
>>1 保存到数据库, 数据库表中对应字段要设置为BLOB类型

>>2 保存到硬盘代码如下

InputStream in = new
FileInputStream( myfile);
OutputStream out = new
FileOutputStream( new File("d:\\upload\\"+myfileFileName));
byte[] buffer
= new byte[ in.available() ];
int ins =
in.read(buffer);//读取字节到buffer中
//ins == -1 时
。就已经是文件的结尾了
while ( ins !=
-1 ) {
out.write(buffer, 0, ins);//将缓存buffer中的数据写到文件中
ins = in.read(buffer);
}

in.close();
out.flush();
out.close();
2,下载
(1), 把要下载的文件转成一个输入流InputStream
例如,利用hibernate取得一个文件,文件类型在实体类中为byte[]类型,

inputStream = new
ByteArrayInputStream(book.getMyfile);
其中inputStream 为全局变量,并且做setter和getter方法
(2),在控制器对应的action节点中(struts2配置文件中)添加一个result节点如下:

<result name="download" type="stream">
<param name="contentType">application/zip</param>

<param name="inputName">inputStream</param>
<param name="contentDisposition">attachment;filename="${myFileFileName}"</param>
<param name="bufferSize">1024</param>
</result>
这样,就可以实现上传和下载了.

❷ 如何实现struts2的文件上传

(upload.jsp)
<body>
<s:form action="loadPage" namespace="/load" enctype="multipart/form-data">
<s:file name="file" label="select a file"></s:file>
<s:textfield name="newFileName" label="文件新名字"></s:textfield>
<s:submit value="提交"></s:submit>
</s:form>
<s:actionerror/>
</body>

(struts-upload.xml)

<package name="load" extends="struts-default" namespace="/load">
<global-results>
<result name="input">/WEB-INF/pages/load/load.jsp</result>
</global-results>

<action name="load" class="com.tj.beef.action.LoadPageAction" method="input">
</action>

<action name="loadPage" class="com.tj.beef.action.LoadPageAction">
<interceptor-ref name="defaultStack">
<param name="fileUpload.maximumSize">102400</param>
<param name="fileUpload.allowedTypes">image/gif,image/pjpeg</param>
</interceptor-ref>
<param name="loadDir">/img/</param>
<result>/WEB-INF/pages/load/success.jsp</result>

</action>
</package>

(LoadPageAction)

package com.tj.beef.action;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class LoadPageAction extends ActionSupport {
private File file;
private String fileFileName;
private String fileContentType;
private String loadDir;
private String newFileName;

public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileContentType() {
return fileContentType;
}

public String getFileFileName() {
return fileFileName;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public void setFileContentType(String fileContentType) {
this.fileContentType = fileContentType;
}
public String getLoadDir() {
return loadDir;
}
public void setLoadDir(String loadDir) {
this.loadDir = loadDir;
}
public String getNewFileName() {
return newFileName;
}
public void setNewFileName(String newFileName) {
this.newFileName = newFileName;
}
@Override
public String execute() throws Exception {
System.out.println(file);
System.out.println(fileFileName);
System.out.println(fileContentType);
System.out.println(loadDir);
System.out.println(newFileName);
//get path
String path = ServletActionContext.getServletContext().getRealPath(this.loadDir);
//hava file?
File dir = new File(path);
if(!dir.exists()) {
dir.mkdir();
}
//
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);

File newFile = new File(path,fileFileName);
FileOutputStream fos = new FileOutputStream(newFile);
BufferedOutputStream bos = new BufferedOutputStream(fos);
//
byte[] buf = new byte[4096];
int len = bis.read(buf);
while(len!=-1) {
bos.write(buf,0,len);
len = bis.read(buf);
}
bis.close();
fis.close();
bos.close();
fos.close();

return SUCCESS;
}
@Override
public String input() throws Exception {
// TODO Auto-generated method stub
return INPUT;
}

}

❸ struts2中在action中怎么对文件上传进行处理

InputStream is = null;
OutputStream ops = null;
for (int i = 0; i < file.size(); i++) {
try {
TFile tfile = new TFile();
if (file.get(i) == null) {
continue;
}
is = new FileInputStream(file.get(i));
//路径
String root = ServletActionContext.getRequest()
.getRealPath("/uploads");
// 根据系统时间取名字
int pos = this.getFileFileName().get(i).lastIndexOf(".");
String ext = this.getFileFileName().get(i).substring(pos);
// 获得系统时间,产生文件名
long now = System.currentTimeMillis();
String nowtime = String.valueOf(now);
File destFile = new File(root + "/", nowtime + ext);
ops = new FileOutputStream(destFile);
byte[] b = new byte[400];
int length = 0;
while ((length = is.read(b)) > 0) {
ops.write(b, 0, length);
// ops.write(b); 这样子同样可行
}
tfile.setFileName(getFileFileName().get(i));
tfile.setFilePath("/uploads/" + nowtime + ext);
tfile.setFileCreatetime(currentDate);
tfile.setFileDataid(uptdt.getDataId());
fileservice.saveFile(tfile);// 保存上传文件信息
} catch (Exception ex) {
ex.printStackTrace();

} finally {
is.close();
ops.close();
}
}

❹ 使用struts2 怎么实现 文件上传到另外一台电脑

传输文件的功能,类似于网络聊天程序。

肯定要用的文件传输用的IO流,还有网络通信用到的socket了。

可以在你部署struts2网站的服务器上面写一个网络通信程序(服务器端),对应的网络通信程序(客户端)放在“另外一台电脑”上面。

网站的服务器启动之后:
1。把那个网络通信程序(服务器端)启动

2。把“另外一台电脑”上面的网络通信程序(客户端)启动,现在两端就建立连接了。

3。可以通过服务器端向客户端发送数据。

以上过程跟我们平时用的聊天程序一样。

你可以在网上看看相应的网络聊天程序,现在网上这样的程序还是很多的。
里面实现了这样的机制。

❺ struts2如何同时上传文件以及获得表单数据

事实上这根本不需要什么其他配置操作,因为这是Struts2,而不是原生Servlet,在Struts2中,拦截器会将request中的表单数据(或者文件格式的数据)都和action类中的属性名称一一对应的注入值(包括文件数据)。所以你需要做的,其实只是在jsp页面(或html)中加入一个file类型的input标签,名称记住(比如为photo),然后在action类中加一个File类型(java.io.File)字段,此字段必须和刚刚的input标签name属性一致,即photo(private File photo;)。最后,需要注意的是,当你妄图从网页上传一个文件类型的表单时,必须将包围它的form类将enctype="multipart/form-data" method="post"加上,即method必须为post,且enctype,也就是表单数据类型,必须为二进制的。

❻ struts2文件上传

可以用随机函数,得到一个随机数,再加上当前的时间,作为一个符号串当文件的文件名,然后把上传的文件取得原来的文件名,截取原来文件名的后缀名,记得连点一起截取,这样就可以把刚才的随机数加时间再加截取得的后缀名作为新的文件名;代码如下:其在action是这样:package huan.lin.shopaction;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Random;import org.apache.struts2.ServletActionContext;import huan.lin.shopbean.Shop;
import huan.lin.shopservice.Shopservice;import com.opensymphony.xwork2.ActionSupport;public class Saveshopaction extends ActionSupport {
private static final long serialVersionUID = -7387264205534303757L; private Shopservice shopservice; private String spname;
private String sppaizi;
private String spms;
private String sppicurl;
private String sphave;
private double spprice;

private File file;
private String fileFileName;
private String fileContentType; @SuppressWarnings("deprecation")
public String execute() throws Exception {

//文件上传
long time = new Date().getTime();
Random ran = new Random();
int newran = ran.nextInt(10000);
InputStream is = new FileInputStream(file);
String sub = this.getFileFileName();
String subname = sub.substring(sub.lastIndexOf(".", sub.length()));
String filename = time + "" + newran + subname;
String root = ServletActionContext.getRequest().getRealPath("/uploadsmallimage");
File destFile = new File(root, filename);
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[4000];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
is.close();
os.close();
//数据保存 Shop shop = new Shop();

shop.setSpname(spname);
shop.setSppaizi(sppaizi);
shop.setSpprice(spprice);
shop.setSphave(sphave);
shop.setSpms(spms);
shop.setSppicurl(filename); this.getShopservice().save(shop);
return SUCCESS;
}
public Shopservice getShopservice() {
return shopservice;
} public void setShopservice(Shopservice shopservice) {
this.shopservice = shopservice;
} public String getSpname() {
return spname;
} public void setSpname(String spname) {
this.spname = spname;
} public String getSpms() {
return spms;
} public void setSpms(String spms) {
this.spms = spms;
} public String getSppicurl() {
return sppicurl;
} public void setSppicurl(String sppicurl) {
this.sppicurl = sppicurl;
} public String getSphave() {
return sphave;
} public void setSphave(String sphave) {
this.sphave = sphave;
}
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 double getSpprice() {
return spprice;
} public void setSpprice(double spprice) {
this.spprice = spprice;
}
public void validate()
{

}
public String getSppaizi() {
return sppaizi;
}
public void setSppaizi(String sppaizi) {
this.sppaizi = sppaizi;
}
}
在servlet中如下: package huan.lin;import java.io.IOException;
import java.sql.SQLException;import java.util.Date;
import java.util.Random;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.sql.DataSource;import org.apache.commons.dbutils.QueryRunner;import com.jspsmart.upload.File;
import com.jspsmart.upload.Files;
import com.jspsmart.upload.SmartUpload;public class PhotouploadServlet extends HttpServlet { private static final long serialVersionUID = -806574948649837705L; public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Users users = (Users) session.getAttribute("users");
if (users == null) {
response.sendRedirect("/lin01/admin/login.jsp");
} else {

request.setCharacterEncoding("utf-8");
String newname = "";
// 新建一个SmartUpload对象
SmartUpload su = new SmartUpload();
// 上传初始化 su.initialize(this.getServletConfig(), request, response);
// 限制每个上传文件的最大长度。 su.setMaxFileSize(600000);
// 限制总上传数据的长度。
// su.setTotalMaxFileSize(200000);
// 设定允许上传的文件(通过扩展名限制),仅允许doc,txt文件。
su.setAllowedFilesList("jpeg,gif,jpg,bmp"); try { su.upload(); Files fes = su.getFiles();
File fe = fes.getFile(0);
String name = fe.getFileName();
String subname = name.substring(name.lastIndexOf("."), name
.length());
long time1 = new Date().getTime();
Random ran = new Random();
int newran = ran.nextInt(10000);
newname = time1 + "" + newran + subname;

ServletContext sc = this.getServletContext();
String path = sc.getRealPath("upload");
fe.saveAs(path+"/"+newname); InitialContext ctx = null;
try {
ctx = new InitialContext();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DataSource ds = null;
try {
ds = (DataSource)ctx.lookup("java:comp/env/jdbc/rollerdb");
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int result = 0; try { String sql = "insert into photo (name) values (?)"; String params[] = { newname };
// DButils中核心类,生成对象时传递数据源对象
QueryRunner qr = new QueryRunner(ds); result = qr.update(sql, params);
} catch (SQLException e) {
e.printStackTrace();
}

String message = "";
if (result == 1) {
message = "Congratulation to you(恭喜你),上传成功!";
} else {
message = "Sorry,上传失败!";
} request.setAttribute("message", message); request.getRequestDispatcher("/photouploadsuccess.jsp").forward(request,
response); } catch (Exception e) {
response.sendRedirect("/lin01/uploadphotoerror.jsp");
} }
}}

❼ struts2 文件上传 ,上传的文件的主键与数据库中的冲突应该怎么处理

在struts2
的action
中增加action的错误
返回input页面
标签输出错误信息
.
this.addActionError(
"
系统错误
"
);
return
INPUT
;
页面用
<s:actionerror/>

❽ 使用struts2如何实现文件上传

  1. 新建Web Project,在WebRoot下新建upload文件夹

  2. 在WebRoot下新建upload.jsp,上传界面

  3. 编写上传成功、失败的提示界面。

  4. 在WebRoot下新建uploadError.jsp

  5. 在WebRoot下新建uploadSuccess.jsp

  6. 编写Action类

  7. 配置struts.xml文件,重置fileUpload拦截器。

  8. 测试,测试完成之后在tomcat下面webapps目录下找到项目对应的文件夹下的upload下查看

❾ 这是一个java中关于struts2文件上传的Action实现类,代码都没错,但好像说找不到什么东西

你截图里面代码左边行数上那些warning都是告诉你整个程序的设置都有错误。

你把鼠标挪到那些红色警示和灯泡上,会有提示告诉你问题在哪儿。(图中:行 6,7,8,19)

比如,你的actionsupport和internal_error那两个import的警示一般表示你的library不存在或者没有放对地方,你应该是有个lib文件或者是jar文件带有这个库但没设置对地点。19行的FileOutputStream是因为你没有import等等。

还有你的excute的最后一行 return SUCCESS; 应该用引号, "SUCCESS"才是表示一个string。

在具体解决你的课题之前,这些语法和设置上的错误要先排除。只要有一个红色的warning在,你都无法正式开始运行程序。

❿ struts2 如何通过ajax上传文件

ajax是不能上传文件的,一般做法是使用一个隐藏的iframe 来个传,达到无刷新上传的效果。
还有就是使用swf上传控件,swfUpload等

热点内容
怎么用安卓手机帮ios刷机 发布:2024-06-27 02:26:20 浏览:631
跑酷服务器电脑版推荐 发布:2024-06-27 02:19:16 浏览:740
java中是什么 发布:2024-06-27 02:15:09 浏览:158
安卓wlan有什么用 发布:2024-06-27 01:58:30 浏览:817
王者荣耀安卓怎么删除我的电脑 发布:2024-06-27 01:57:53 浏览:613
用什么软件可以升级配置 发布:2024-06-27 01:45:42 浏览:546
账号编程 发布:2024-06-27 01:43:36 浏览:551
矩阵压缩存储为了 发布:2024-06-27 01:42:37 浏览:547
python字典嵌套列表 发布:2024-06-27 01:42:26 浏览:761
vcs编译后报错 发布:2024-06-27 01:36:53 浏览:463