导航:首页 > 文件教程 > struts2输出文件流

struts2输出文件流

发布时间:2024-04-11 05:37:26

① struts2+ajax锛宎ction涓璷ut.write()鐨勯棶棰

鍦⊿TRUTS2涓锛屽皢璇锋眰瀵硅薄request鍜屽搷搴斿硅薄response鍋氫簡闈欐佺殑灏佽咃紝涓嶅啀鏄娴佸硅薄浜嗭紝鎵浠ヤ笉鑳藉儚STRUTS1涓閭f牱褰撴祦瀵硅薄浣跨敤浣跨敤.

瑕佹兂瀹屾垚浣犳墍闇瑕佺殑锛屼綘鍙浠ュ湪action涓瀹氫箟涓涓鍏ㄥ眬鐨勫彉閲忥紝灏嗗叾璧嬪硷紝鐒跺悗鐩存帴鍦ㄥ瑰簲鐨凧SP鎺ュ彈鍗冲彲銆
鍙﹀栵紝瑕佸皢redirect淇鏀逛负dispatcher锛屽洜涓簉edirect涓洪噸瀹氬悜锛屽叾涓嶈兘淇濆瓨浠庡墠涓涓猘ction澶勭悊杩囩殑鍙傛暟.

② struts2产生验证码时, 绘图BufferedImage对象 已经弄好了,发送的用什么输出流呢

可以用ImageIO:
response.setContentType("image/jpeg");
OutputStream ops=response.getOutputStream();
javax.imageio.ImageIO.write(image, "jpeg", ops);

③ 得到file的文件名和存储路径后,在Struts2中的action中要怎样获取file的内容并显示到action转到的jsp页面中

struts2单文件上传:
首先是一个文件上传页面,这个比较简单,就是一个表单,里面有个文件上传框

<!--在进行文件上传时,表单提交方式一定要是post的方式,因为文件上传时二进制文件可能会很大,还有就是enctype属性,这个属性一定要写成multipart/form-data,
不然就会以二进制文本上传到服务器端-->
<form action="fileUpload.action" method="post" enctype="multipart/form-data">

username: <input type="text" name="username"><br>
file: <input type="file" name="file"><br>

<input type="submit" value="submit">
</form>

接下来是FileUploadAction部分代码,因为struts2对上传和下载都提供了很好的实习机制,所以在action这段我们只需要写很少的代码就行:

public class FileUploadAction extends ActionSupport
{
private String username;
//注意,file并不是指前端jsp上传过来的文件本身,而是文件上传过来存放在临时文件夹下面的文件
private File file;

//提交过来的file的名字
private String fileFileName;

//提交过来的file的MIME类型
private String fileContentType;

public String getUsername()
{
return username;
}

public void setUsername(String username)
{
this.username = username;
}

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;
}

@Override
public String execute() throws Exception
{
String root = ServletActionContext.getServletContext().getRealPath("/upload");

InputStream is = new FileInputStream(file);

OutputStream os = new FileOutputStream(new File(root, fileFileName));

System.out.println("fileFileName: " + fileFileName);

// 因为file是存放在临时文件夹的文件,我们可以将其文件名和文件路径打印出来,看和之前的fileFileName是否相同
System.out.println("file: " + file.getName());
System.out.println("file: " + file.getPath());

byte[] buffer = new byte[500];
int length = 0;

while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}

os.close();
is.close();

return SUCCESS;
}
}

首先我们要清楚一点,这里的file并不是真正指代jsp上传过来的文件,当文件上传过来时,struts2首先会寻找struts.multipart.saveDir(这个是在default.properties里面有)这个name所指定的存放位置,我们可以新建一个struts.properties属性文件来指定这个临时文件存放位置,如果没有指定,那么文件会存放在tomcat的apache-tomcat-7.0.29\work\Catalina\localhost\目录下,然后我们可以指定文件上传后的存放位置,通过输出流将其写到流里面就行了,这时我们就可以在文件夹里看到我们上传的文件了。
文件上传后我们还需要将其下载下来,其实struts2的文件下载原理很简单,就是定义一个输入流,然后将文件写到输入流里面就行,关键配置还是在struts.xml这个配置文件里配置:
FileDownloadAction代码如下:

public class FileDownloadAction extends ActionSupport
{
public InputStream getDownloadFile()
{
return ServletActionContext.getServletContext().getResourceAsStream("upload/通讯录2012年9月4日.xls");
}

@Override
public String execute() throws Exception
{
return SUCCESS;
}
}

我们看,这个action只是定义了一个输入流,然后为其提供getter方法就行,接下来我们看看struts.xml的配置文件:
<action name="fileDownload" class="com.xiaoluo.struts2.FileDownloadAction">
<result name="success" type="stream">
<param name="contentDisposition">attachment;filename="通讯录2012年9月4日.xls"</param>
<param name="inputName">downloadFile</param>
</result>
</action>

struts.xml配置文件有几个地方我们要注意,首先是result的类型,以前我们定义一个action,result那里我们基本上都不写type属性,因为其默认是请求转发(dispatcher)的方式,除了这个属性一般还有redirect(重定向)等这些值,在这里因为我们用的是文件下载,所以type一定要定义成stream类型,告诉action这是文件下载的result,result元素里面一般还有param子元素,这个是用来设定文件下载时的参数,inputName这个属性就是得到action中的文件输入流,名字一定要和action中的输入流属性名字相同,然后就是contentDisposition属性,这个属性一般用来指定我们希望通过怎么样的方式来处理下载的文件,如果值是attachment,则会弹出一个下载框,让用户选择是否下载,如果不设定这个值,那么浏览器会首先查看自己能否打开下载的文件,如果能,就会直接打开所下载的文件,(这当然不是我们所需要的),另外一个值就是filename这个就是文件在下载时所提示的文件下载名字。在配置完这些信息后,我们就能过实现文件的下载功能了。

struts2多文件上传:
其实多文件上传和单文件上传原理一样,单文件上传过去的是单一的File,多文件上传过去的就是一个List<File>集合或者是一个File[]数组,首先我们来看一下前端jsp部分的代码,这里我用到了jquery来实现动态的添加文件下载框以及动态的删除下载框:

<script type="text/javascript" src="script/jquery-1.8.1.js"></script>
<script type="text/javascript">

$(function()
{
$("#button").click(function()
{
var html = $("<input type='file' name='file'>");
var button = $("<input type='button' name='button' value='删除'><br>");

$("#body div").append(html).append(button);

button.click(function()
{
html.remove();
button.remove();
})
})
})

</script>
</head>

<body id="body">

<form action="fileUpload2.action" method="post" enctype="multipart/form-data">

username: <input type="text" name="username"><br>
file: <input type="file" name="file">
<input type="button" value="添加" id="button"><br>
<div></div>
<input type="submit" value="submit">

</form>

</body>

file的名字必须都命名成file才行,然后处理多文件上传的action代码如下:

public class FileUploadAction2 extends ActionSupport
{
private String username;
//这里用List来存放上传过来的文件,file同样指的是临时文件夹中的临时文件,而不是真正上传过来的文件
private List<File> file;
//这个List存放的是文件的名字,和List<File>中的文件相对应
private List<String> fileFileName;

private List<String> fileContentType;

public String getUsername()
{
return username;
}

public void setUsername(String username)
{
this.username = username;
}

public List<File> getFile()
{
return file;
}

public void setFile(List<File> file)
{
this.file = file;
}

public List<String> getFileFileName()
{
return fileFileName;
}

public void setFileFileName(List<String> fileFileName)
{
this.fileFileName = fileFileName;
}

public List<String> getFileContentType()
{
return fileContentType;
}

public void setFileContentType(List<String> fileContentType)
{
this.fileContentType = fileContentType;
}

@Override
public String execute() throws Exception
{
String root = ServletActionContext.getServletContext().getRealPath("/upload");

for(int i = 0; i < file.size(); i++)
{
InputStream is = new FileInputStream(file.get(i));

OutputStream os = new FileOutputStream(new File(root, fileFileName.get(i)));

byte[] buffer = new byte[500];

@SuppressWarnings("unused")
int length = 0;

while(-1 != (length = is.read(buffer, 0, buffer.length)))
{
os.write(buffer);
}

os.close();
is.close();
}

return SUCCESS;
}
}

这样同样将其写到一个输出流里面,这样我们就可以在文件夹里看到上传的多个文件了

④ java中怎么利用struts2上传多个pdf文件

通过3种方式模拟多个文件上传
第一种方式
package com.ljq.action;
import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class UploadAction extends ActionSupport{
private File[] image; //上传的文件
private String[] imageFileName; //文件名称
private String[] imageContentType; //文件类型
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
String realpath = ServletActionContext.getServletContext().getRealPath("/images");
System.out.println(realpath);
if (image != null) {
File savedir=new File(realpath);
if(!savedir.getParentFile().exists())
savedir.getParentFile().mkdirs();
for(int i=0;i<image.length;i++){
File savefile = new File(savedir, imageFileName[i]);
FileUtils.File(image[i], savefile);
}
ActionContext.getContext().put("message", "文件上传成功");
}
return "success";
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
}
第二种方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用数组上传多个文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction2 extends ActionSupport{
private File[] image; //上传的文件
private String[] imageFileName; //文件名称
private String[] imageContentType; //文件类型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
//取得需要上传的文件数组
File[] files = getImage();
if (files !=null && files.length > 0) {
for (int i = 0; i < files.length; i++) {
//建立上传文件的输出流, getImageFileName()[i]
System.out.println(getSavePath() + "\\" + getImageFileName()[i]);
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName()[i]);
//建立上传文件的输入流
FileInputStream fis = new FileInputStream(files[i]);
byte[] buffer = new byte[1024];
int len = 0;
while ((len=fis.read(buffer))>0) {
fos.write(buffer, 0, len);
}
fos.close();
fis.close();
}
}
return SUCCESS;
}
public File[] getImage() {
return image;
}
public void setImage(File[] image) {
this.image = image;
}
public String[] getImageFileName() {
return imageFileName;
}
public void setImageFileName(String[] imageFileName) {
this.imageFileName = imageFileName;
}
public String[] getImageContentType() {
return imageContentType;
}
public void setImageContentType(String[] imageContentType) {
this.imageContentType = imageContentType;
}
/**
* 返回上传文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
第三种方式
package com.ljq.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
/**
* 使用List上传多个文件
*
* @author ljq
*
*/
@SuppressWarnings("serial")
public class UploadAction3 extends ActionSupport {
private List<File> image; // 上传的文件
private List<String> imageFileName; // 文件名称
private List<String> imageContentType; // 文件类型
private String savePath;
@Override
public String execute() throws Exception {
ServletActionContext.getRequest().setCharacterEncoding("UTF-8");
// 取得需要上传的文件数组
List<File> files = getImage();
if (files != null && files.size() > 0) {
for (int i = 0; i < files.size(); i++) {
FileOutputStream fos = new FileOutputStream(getSavePath() + "\\" + getImageFileName().get(i));
FileInputStream fis = new FileInputStream(files.get(i));
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fis.close();
fos.close();
}
}
return SUCCESS;
}
public List<File> getImage() {
return image;
}
public void setImage(List<File> image) {
this.image = image;
}
public List<String> getImageFileName() {
return imageFileName;
}
public void setImageFileName(List<String> imageFileName) {
this.imageFileName = imageFileName;
}
public List<String> getImageContentType() {
return imageContentType;
}
public void setImageContentType(List<String> imageContentType) {
this.imageContentType = imageContentType;
}
/**
* 返回上传文件保存的位置
*
* @return
* @throws Exception
*/
public String getSavePath() throws Exception {
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
}
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>
<!-- 该属性指定需要Struts2处理的请求后缀,该属性的默认值是action,即所有匹配*.action的请求都由Struts2处理。
如果用户需要指定多个请求后缀,则多个后缀之间以英文逗号(,)隔开。 -->
<constant name="struts.action.extension" value="do" />
<!-- 设置浏览器是否缓存静态内容,默认值为true(生产环境下使用),开发阶段最好关闭 -->
<constant name="struts.serve.static.browserCache" value="false" />
<!-- 当struts的配置文件修改后,系统是否自动重新加载该文件,默认值为false(生产环境下使用),开发阶段最好打开 -->
<constant name="struts.configuration.xml.reload" value="true" />
<!-- 开发模式下使用,这样可以打印出更详细的错误信息 -->
<constant name="struts.devMode" value="true" />
<!-- 默认的视图主题 -->
<constant name="struts.ui.theme" value="simple" />
<!--<constant name="struts.objectFactory" value="spring" />-->
<!--解决乱码 -->
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.multipart.maxSize" value="10701096"/>
<package name="upload" namespace="/upload" extends="struts-default">
<action name="*_upload" class="com.ljq.action.UploadAction" method="{1}">
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload1" namespace="/upload1" extends="struts-default">
<action name="upload1" class="com.ljq.action.UploadAction2" method="execute">
<!-- 要创建/image文件夹,否则会报找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
<package name="upload2" namespace="/upload2" extends="struts-default">
<action name="upload2" class="com.ljq.action.UploadAction3" method="execute">
<!-- 要创建/image文件夹,否则会报找不到文件 -->
<param name="savePath">/image</param>
<result name="success">/WEB-INF/page/message.jsp</result>
</action>
</package>
</struts>
上传表单页面upload.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<!-- ${pageContext.request.contextPath}/upload/execute_upload.do -->
<!-- ${pageContext.request.contextPath}/upload1/upload1.do -->
<!-- ${pageContext.request.contextPath}/upload2/upload2.do -->
<!-- -->
<form action="${pageContext.request.contextPath}/upload2/upload2.do" enctype="multipart/form-data" method="post">
文件1:<input type="file" name="image"><br/>
文件2:<input type="file" name="image"><br/>
文件3:<input type="file" name="image"><br/>
<input type="submit" value="上传" />
</form>
</body>
</html>
显示页面message.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'message.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
上传成功
<br/>
<s:debug></s:debug>
</body>
</html>

⑤ struts2的action中去访问一个文件,下载到本地

要通过param来写
<result type="redirectAction">
<param name="namespace">/p1</param> (这里内要写package的容namespace)
<param name="actionName">a1</param> (这里写action的name)
</result>

⑥ 使用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下查看

⑦ struts2怎么返回json数据

<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEstrutsPUBLIC
"-//ApacheSoftwareFoundation//DTDStrutsConfiguration2.1//EN"
"
<struts>
<packagename=""extends="json-default"namespace="">


<actionname=""class=""method="">
<resulttype="json">
以下是变量名为loginUser对象的某些指定属性
<paramname="includeProperties">
loginUser.id,
loginUser.loginName,
loginUser.name,
loginUser.roleNames
</param>

以下是变量名为loginUser对象的全部属性,多个对象用逗号
<paramname="includeProperties">
loginUser.*,
loginUser1.*
</param>

以下是集合里的某些指定属性
<paramname="includeProperties">
weekScheles[d+].id,
weekScheles[d+].startDate,
weekScheles[d+].endDate,
weekScheles[d+].title,
weekScheles[d+].scheleCount
</param>
</result>
</action>
</package>
</struts>

注意package标签,extends要写成json-default

Struts2处理JSON只需要在xml文件里就可以完成,但是要注意,能够直接作为JSON返回的必须是Action类里的属性,方法中的属性不能使用此方式直接返回

阅读全文

与struts2输出文件流相关的资料

热点内容
免费在线观看网站网址 浏览:565
钢琴女老师韩国 浏览:858
文件保存路径能修改嘛 浏览:518
wds有哪些文件 浏览:77
linux进bios重做系统 浏览:811
清华电子计算机网络 浏览:453
360无法升级 浏览:826
被渔民强奸的电影 浏览:34
大数据商业变革 浏览:510
社工库qq群数据库2017 浏览:844
圆管切圆孔激光怎么编程 浏览:560
手机钉钉下载下来的文件在哪里找 浏览:545
男主是女主的三叔 浏览:514
经济师万题库大数据 浏览:996
获取appsetting 浏览:920
苹果7plus哪个颜色保值 浏览:869
蜜桃风月 浏览:533
1个电影多少流量 浏览:971
日本瑜伽电影 浏览:463
有一部电影讲一个男的做鸭 浏览:247

友情链接