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

struts2如何上傳文件

發布時間: 2023-03-04 05:04:33

① 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實現多圖片上傳

新建Web Project,在WebRoot下新建upload文件夾
在WebRoot下新建upload.jsp,上傳界面

編寫上傳成功、失敗的提示界面。
在WebRoot下新建uploadError.jsp

在WebRoot下新建 uploadSuccess.jsp

編寫Action類

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

測試,測試完成之後在tomcat下面webapps目錄下找到項目對應的文件夾下的upload下查看

③ 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();
}

④ 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上傳文件保存到資料庫中

1在你的struts-config中首先不能使用form,使用的話會報錯
2在你jsp的form中增加屬性enctype="multipart/form-data"
這樣你的文件內容會被都城二進制數據傳到後台,在後台獲取值保存及可以了

熱點內容
ct4哪個配置性價比最高 發布:2025-05-19 15:38:02 瀏覽:952
如何設置強緩存的失效時間 發布:2025-05-19 15:21:28 瀏覽:695
winxp無法訪問 發布:2025-05-19 15:19:48 瀏覽:947
文件預編譯 發布:2025-05-19 15:14:04 瀏覽:643
怎麼在伺服器上掛公網 發布:2025-05-19 15:14:02 瀏覽:272
濟南平安e通如何找回密碼 發布:2025-05-19 14:56:58 瀏覽:176
安卓手機如何找到iccid碼 發布:2025-05-19 14:46:51 瀏覽:227
編譯的內核為什麼那麼大 發布:2025-05-19 14:45:21 瀏覽:179
什麼控制壓縮 發布:2025-05-19 14:28:13 瀏覽:931
網路伺服器忙指什麼 發布:2025-05-19 14:28:10 瀏覽:189