當前位置:首頁 » 文件管理 » 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等

熱點內容
swift和python 發布:2024-06-29 19:10:09 瀏覽:418
安卓音樂播放器q什麼 發布:2024-06-29 18:52:18 瀏覽:743
大加密箱 發布:2024-06-29 18:49:09 瀏覽:646
python類中的變數初始化 發布:2024-06-29 18:49:06 瀏覽:933
linux論壇的搭建 發布:2024-06-29 18:40:21 瀏覽:733
晚清民國期刊資料庫 發布:2024-06-29 18:26:39 瀏覽:705
京東支付登錄密碼是多少 發布:2024-06-29 17:40:58 瀏覽:167
蘋果13寸pro買哪個配置 發布:2024-06-29 17:37:20 瀏覽:978
電腦做ftp 發布:2024-06-29 17:25:14 瀏覽:376
linux伺服器管理系統 發布:2024-06-29 17:20:03 瀏覽:609