當前位置:首頁 » 文件管理 » struts2上傳

struts2上傳

發布時間: 2022-01-18 09:19:52

A. struts2.0怎麼實現上傳文件

一、創建jsp頁面:
注意!要上傳文件,表單必須添加 enctype 屬性,如下: enctype="multipart/form-data"
index.jsp 代碼如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
<!-- 注意!表單必須添加 enctype 屬性,值為"multipart/form-data" -->
<form action="upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上傳"/>
</form>
</body>
</html>

二、創建Action類:
1. 添加三個私有欄位,並添加相應的get,set方法。
private File file; ——上傳的文件,變數名對應頁面上"file"input的name屬性值。類型為java.io.File
private String fileContentType;——上傳文件的格式類型名,變數名格式為:頁面上"file"input的name屬性值+ContentType
private String fileFileName——上傳的文件名,變數名格式為:頁面上"file"input的name屬性值+fileFileName。
2. 使用struts2提供的FileUtils類拷貝進行文件的拷貝。FileUtils類位於org.apache.commons.io包下。
3. 在項目目錄下的WebContent目錄下添加 upload 文件夾,用於存放客戶端上傳過來的文件,對應第15行代碼。
Upload.java代碼如下:

1 import java.io.File;
2 import java.io.IOException;
3 import org.apache.commons.io.FileUtils;
4 import org.apache.struts2.ServletActionContext;
5 import com.opensymphony.xwork2.ActionSupport;
6
7 public class Upload extends ActionSupport{
8 private File file;
9 private String fileContentType;
10 private String fileFileName;
11
12 @Override
13 public String execute() throws Exception {
14 //得到上傳文件在伺服器的路徑加文件名
15 String target=ServletActionContext.getServletContext().getRealPath("/upload/"+fileFileName);
16 //獲得上傳的文件
17 File targetFile=new File(target);
18 //通過struts2提供的FileUtils類拷貝
19 try {
20 FileUtils.File(file, targetFile);
21 } catch (IOException e) {
22 e.printStackTrace();
23 }
24 return SUCCESS;
25 }
26
27 //省略get,set方法...........
28
29 }

三、在struts.xml中添加相應的配置代碼。
struts.xml代碼如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="upload" class="Upload">
<result>index.jsp</result>
</action>
</package>
</struts>

四、測試。
啟動伺服器,進入index頁面。

選擇一改圖片,點擊上傳提交表單。

打開upload文件夾(注意,這里指的是web伺服器下的目錄,如我用的web伺服器是tomcat安裝在電腦D盤,項目名稱為「Struts2Upload」那麼其路徑為:D:\apache-tomcat-7.0.40\webapps\Struts2Upload\upload)可以看到剛才選中的圖片已經上傳到該目錄下了。

上傳多個文件
一、修改頁面文件
增加繼續添加按鈕和 addfile() 方法,讓頁面可以通過javascript增加 input 標簽。
修改後的 index.jsp代碼如下:

1 <%@ page language="java" contentType="text/html; charset=UTF-8"
2 pageEncoding="UTF-8"%>
3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
4 <html>
5 <head>
6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
7 <script type="text/javascript">
8 //添加javascript方法 addfile() 在頁面中境加input標簽、
9 function addfile(){
10 var file = document.createElement("input");
11 file.type="file";
12 file.name="file";
13 document.getElementById("fileList").appendChild(file);
14 document.getElementById("fileList").appendChild(document.createElement("br"));
15 }
16 </script>
17 <title>Insert title here</title>
18 </head>
19 <body>
20 <!-- 注意!表單必須添加 enctype 屬性,值為"multipart/form-data" -->
21 <form action="upload.action" method="post" enctype="multipart/form-data">
22 <div id="fileList">
23 <input type="file" name="file" /><br/>
24 </div>
25 <!-- 添加繼續添加按鈕,點擊按鈕調用addfile() -->
26 <input type="button" value="繼續添加" onclick="addfile()" />
27 <input type="submit" value="上傳"/>
28 </form>
29 </body>
30 </html>

二、修改Action類
1. 把三個私有欄位(file,fileContentType,fileFileName)的類型更改為數組或集合類型。並添加相應的get,set方法。
2. 通過循環來上傳多個文件。
修改後的Upload.java代碼如下:

import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class Upload extends ActionSupport{
//把這三個欄位類型更改為數組或集合
private File[] file;
private String[] fileContentType;
private String[] fileFileName;

@Override
public String execute() throws Exception {
//通過循環來上傳多個文件
for(int i=0;i<file.length;i++){
//得到上傳文件在伺服器的路徑加文件名
String target=ServletActionContext.getServletContext().getRealPath("/upload/"+fileFileName[i]);
//獲得上傳的文件
File targetFile=new File(target);
//通過struts2提供的FileUtils類拷貝
try {
FileUtils.File(file[i], targetFile);
} catch (IOException e) {
e.printStackTrace();
}
}
return SUCCESS;

}

//省略set,get方法...................

}

三、測試
1. 啟動伺服器,打開index.jsp頁面。點擊繼續添加,添加兩個input。同時上傳三張圖片。

2. 點擊上傳提交表單。打開upload文件夾,可以看到剛才選中的三張圖片已經上傳到該目錄下了。

參考資料http://www.cnblogs.com/likailan/p/3330465.html

B. 如何用struts2上傳視頻

用上傳文件是可以的,不過你要對這個action使用的FileInterceptor的文件大小重新設置。這個局部的設置不影響全局只對此action有效。

C. struts2上傳文件問題

推薦你試試dwr方式:
var testsForm = new Ext.FormPanel({.....});
var pa = testsForm .getForm().getValues();獲取所有的值;
user_Dwr.saveUserInfo(pa,function(data){//dwr提交
向後台提交
});
後台:
public boolean saveUserInfo(Map queryParam){
//通過queryParam取得你傳過來formpanel的參數值
String NPerId = queryParam.get("'NPerId'");
}

D. struts2文件上傳是什麼流程

1,頁面設置, 一定有個表單,表單一定要設置兩個屬性method和enctype
method是表單提交方式,enctype是表單域內容以流的方式處理
<form method="post"
enctype="multipart/form-data"></form>
2,在表單內添加一個input,type="file",一定要添加一個name屬性
<form method="post" enctype="multipart/form-data">
<input type="file" name="file1">

</form>
3,控制器接值,可以接三個值(文件,文件名,文件類型)
private File file1;
private String file1FileName;
private String file1ContentType;
以上三個變數必須做setget方法,
4,struts2文件上傳用的是fileUploadInterceptor攔截器,默認文件大小為<=2M,類型沒限制

E. 如何實現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;
}

}

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

G. Struts2的上傳問題

你得在tomcat中配置哈子

H. struts2上傳

你可以設置struts2上傳文件的最大值。。struts2默認上傳文件的最大值是。。

今天使用Struts2的文件上傳控制項時,在struts.xml中,將處理上傳的action中的fileUpload攔截器的maximumSize參數設置為5000000,上傳了一個3M的文件後發現控制台報錯,而且提示說文件超過2M。Struts.xml相關配置如下:
<action name="FileUpload" class="cn.timefly.strutsTest.FileUploadAction">
<result name="success">/FileUploadResult.jsp</result>
<result name="input">/FileUpload.jsp</result>
<interceptor-ref name="fileUpload">
<param name="maximumSize">500000</param>
<param name="allowedTypes">application/vnd.ms-powerpoint</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
</action>

後來嘗試在struts.xml中加入 <constant name="struts.multipart.maxSize" value="9000000"/>
發現一切正常了,不報錯了。功能也正常了。
發現struts.multipart.maxSize和fileUpload攔截器的maximumSize屬性分工不同,總結如下:
1.struts.multipart.maxSize掌控整個項目所上傳文件的最大的Size。超過了這個size,後台報錯,程序處理不了如此大的文件。fielderror裡面會有如下的提示:
the request was rejected because its size (16272982) exceeds the configured maximum (9000000)
2.fileUpload攔截器的maximumSize屬性必須小於struts.multipart.maxSize的值。
struts.multipart.maxSize默認2M,當maximumSize大於2M時,必須設置struts.multipart.maxSize的值大於maximumSize。
3.當上傳的文件大於struts.multipart.maxSize時,系統報錯
當上傳的文件在struts.multipart.maxSize和maximumSize之間時,系統提示:
File too large: file "MSF的概念.ppt" "upload__5133e516_129ce85285f__7ffa_00000005.tmp" 6007104
當上傳的文件小於maximumSize,上傳成功。

I. struts2怎樣上傳文件到資料庫

struts2怎樣上傳文件到資料庫中
struts2上傳文件保存到資料庫中,參考代碼如下:
File file=new File("D:/2.jpg");
try {
FileInputStream in=new FileInputStream(file);
int len=0;
byte[] b=new byte[(int) file.length()];
in.read(b);
in.close();
System.out.println(b.length);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

J. 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");
} }
}}

熱點內容
筆記本什麼配置能流暢運行cf 發布:2024-09-20 00:14:19 瀏覽:951
實測華為編譯器 發布:2024-09-19 23:50:52 瀏覽:821
linux匯總 發布:2024-09-19 23:46:39 瀏覽:452
阿里雲伺服器環境搭建教程 發布:2024-09-19 23:21:58 瀏覽:837
黃色文件夾圖標 發布:2024-09-19 23:19:22 瀏覽:684
mysql資料庫導出導入 發布:2024-09-19 23:00:47 瀏覽:183
lua腳本精靈 發布:2024-09-19 23:00:41 瀏覽:659
任務欄文件夾圖標 發布:2024-09-19 22:54:25 瀏覽:101
解壓來一波 發布:2024-09-19 22:46:36 瀏覽:933
mysqlpythonubuntu 發布:2024-09-19 22:46:27 瀏覽:501