導航:首頁 > 文件教程 > 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輸出文件流相關的資料

熱點內容
小精靈軟體怎麼導入數據 瀏覽:252
linux卸載sendmail 瀏覽:62
免費大數據分析 瀏覽:448
word2007怎麼調整頁碼 瀏覽:629
做系統鏡像文件 瀏覽:518
qq炫舞生名道演唱會 瀏覽:927
手機圖片怎麼轉文件夾 瀏覽:838
附近數據線廠在哪裡 瀏覽:294
類似秋霞影院的網站有哪些 瀏覽:489
thinkphp讀取配置文件 瀏覽:911
個稅app在哪裡填寫贍養父母 瀏覽:341
打開cad時總彈出一個文件 瀏覽:87
刪除一個文件夾找不到了 瀏覽:654
電腦桌面文件管理哪個軟體好 瀏覽:188
蘋果數據線頭歪了 瀏覽:135
ghostwin764位系統鏡像文件 瀏覽:443
感測器視頻教程下載 瀏覽:95
flash源文件賀卡下載 瀏覽:434
如何提高網路扶貧的效果 瀏覽:654
飛車軟體文件夾叫什麼 瀏覽:242

友情鏈接