當前位置:首頁 » 文件管理 » javastruts2上傳圖片

javastruts2上傳圖片

發布時間: 2023-02-02 06:04:17

1. java Struts2 根據文件路徑可以上傳附件嗎

示例代碼:
imForm = () form;
FormFile importFile = imForm.getImportFile();
InputStream is = importFile.getInputStream();

String store_path = request.getSession().getServletContext().getRealPath("/");
String relativePath = "fileupload/smartheat/profitInfo/ServiceProfitInfo_" + nowtime + ".xls";
String filePath = store_path + relativePath;
OutputStream os = new FileOutputStream(filePath);
int bytes = 0;
byte[] buffer = new byte[is.available()];
while((bytes=is.read(buffer, 0, is.available()))!=-1) {
os.write(buffer,0,bytes);
}

2. java的struts2上傳文件時為什麼這么些、寫

String path = ServletActionContext.getServletContext().getRealPath("/images");
這樣的寫法是為了得到/images的絕對路徑
而String path="/images";這就是相對路徑了,有時候,可能這種寫法程序找不到。

3. 用java完成圖片多張批量上傳的功能,還有就是後台的應該怎麼處理上傳的照片。

環境准備

1. 下載並安裝Tomcat(已經有很多關於Tomcat安裝以及使用的文章,在這里不再介紹);

2. 下載File upload的jar包commons-fileupload-1.0-beta-1.jar,並將該文件拷貝到{$TOMCAT}/common/lib目錄下(其中{$TOMCAT}為Tomcat的安裝目錄);

3. 由於Fileupload子項目同時要用到另外一個項目commons-Beanutils,所以必須下載Beanutils,並將解壓後的文件commons-beanutils.jar拷貝到{$TOMCAT}/common/lib目錄下。

開發文件上傳頁面

文件上傳的界面如圖1所示。為了增加效率我們設計了三個文件域,同時上傳三個文件。
圖1 文件上傳界面

頁面的HTML代碼如下:

<html>
<head>
<title>文件上傳演示</title>
</head>
<body bgcolor=「#FFFFFF」text=「#000000」 leftmargin=「0」topmargin=「40」marginwidth=「0」 marginheight=「0」>
<center>
<h1>文件上傳演示</h1>
<form name=「uploadform」method=「POST」 action=「save.jsp」ENCTYPE=「multipart/form-data」>
<table border=「1」width=「450」cellpadding=「4」 cellspacing=「2」bordercolor=「#9BD7FF」>
<tr><td width=「100%」colspan=「2」>
文件1:<input name=「file1」size=「40」type=「file」>
</td></tr>
<tr><td width=「100%」colspan=「2」>
文件2:<input name=「file2」size=「40」type=「file」>
</td></tr>
<tr><td width=「100%」colspan=「2」>
文件3:<input name=「file3」size=「40」type=「file」>
</td></tr>
</table>
<br/><br/>
<table>
<tr><td align=「center」><input name=「upload」 type=「submit」value=「開始上傳」/></td></tr>
</table>
</form>
</center>
</body>
</html>

代碼中要特別注意的是黑體處。必須保證表單的ENCTYPE屬性值為multipart/form-data,這樣瀏覽器才能正確執行上傳文件的操作。

處理上傳文件信息

由於本文主要是講述如何使用Commons-fileupload,所以為了便於修改、調試,上傳文件的保存使用一個JSP文件來進行處理。我們將瀏覽器上傳來的所有文件保存在一個指定目錄下並在頁面上顯示所有上傳文件的詳細信息。保存頁面處理結果見圖2所示。
圖2 保存頁面

下面來看看save.jsp的代碼:

<%
/**
* 演示文件上傳的處理
* @author <a href=「mailto:[email protected]」>Winter Lau</a>
* @version $Id: save.jsp,v 1.00 2003/03/01 10:10:15
*/
%>
<%@ page language=「java」contentType=「text/html;charset=GBK」%>
<%@ page import=「java.util.*」%>
<%@ page import=「org.apache.commons.fileupload.*」%>
<html>
<head>
<title>保存上傳文件</title>
</head>
<%
String msg = 「」;
FileUpload fu = new FileUpload();
// 設置允許用戶上傳文件大小,單位:位元組
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath(「C:\\TEMP」);
//開始讀取上傳信息
List fileItems = fu.parseRequest(request);
%>
<body bgcolor=「#FFFFFF」text=「#000000」 leftmargin=「0」topmargin=「40」marginwidth=「0」 marginheight=「0」>
<font size=「6」color=「blue」>文件列表:</font>
<center>
<table cellpadding=0 cellspacing=1 border=1 width=「100%」>
<tr>
<td bgcolor=「#008080」>文件名</td>
<td bgcolor=「#008080」>大小</td>
</tr>
<%
// 依次處理每個上傳的文件
Iterator iter = fileItems.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
//忽略其他不是文件域的所有表單信息
if (!item.isFormField()) {
String name = item.getName();
long size = item.getSize();
if((name==null||name.equals(「」)) && size==0)
continue;
%>
<tr>
<td><%=item.getName()%></td>
<td><%=item.getSize()%></td>
</tr>
<%
//保存上傳的文件到指定的目錄
name = name.replace(『:』,『_』);
name = name.replace(『\\』,『_』);
item.write(「F:\\」+ name);
}
}
%>
</table>

<br/><br/>
<a href=「upload.html」>返回上傳頁面</a>
</center>
</body>
</html>

在這個文件中需要注意的是FileUpload對象的一些參數值的意義,如下面代碼所示的三個參數sizeMax、sizeThreshold、repositoryPath:

FileUpload fu = new FileUpload();
// 設置允許用戶上傳文件大小,單位:位元組
fu.setSizeMax(10000000);
// maximum size that will be stored in memory?
// 設置最多隻允許在內存中存儲的數據,單位:位元組
fu.setSizeThreshold(4096);
// 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄
fu.setRepositoryPath(「C:\\TEMP」);

這3個參數的意義分別為:

SizeMax 用來設置上傳文件大小的最大值,一旦用戶上傳的文件大小超過該值時將會拋出一個FileUploadException異常,提示文件太大;

SizeThreshold 設置內存中緩沖區的大小,一旦文件的大小超過該值的時候,程序會自動將其它數據存放在repositoryPath指定的目錄下作為緩沖。合理設置該參數的值可以保證伺服器穩定高效的運行;

RepositoryPath 指定緩沖區目錄。

使用注意事項
從實際應用的結果來看該模塊能夠穩定高效的工作。其中參數SizeThreshold的值至關重要,設置太大會佔用過多的內存,設置太小會頻繁使用硬碟作為緩沖以致犧牲性能。因此,設置該值時要根據用戶上傳文件大小分布情況來設定。例如大部分文件大小集中在100KB左右,則可以使用100KB作為該參數的值,當然了再大就不合適了。使用commons-fileupload來處理HTTP文件上傳的功能模塊很小,但是值得研究的東西很多。

4. struts2上傳圖片到linux伺服器,成功上傳文件,無法返迴路徑,報錯: net::ERR_CONTENT_LENGTH_MISMATCH

因為windows和linux系統的文件路徑分割符是不一樣的。一個是「/」一個是「\」,所以換了環境當熱會錯。java中有一個方法叫做File.separator可以得到是運行環境下的分隔符,你需要在代碼中做出修改。將文件路徑拆開後然後使用 File.separator拼接。

5. Struts2下上傳圖片附件大小驗證問題

提交的時候 可以用 AJAX驗證 上傳文件大小,超出限制直接用JS可以給出提示。
JS沒有辦法獲取文件的大小,因為JS無法操作文件。

6. java struts2 上傳時候的代碼中action =""引號中的意思是什麼

${pageContext.request.contextPath}

得到當前web應用訪問名稱


後面跟的是一個action的訪問方式


這樣看,struts.xml中upload_execute這個Action所在的父級package標簽中應該有namespace應該是這樣:

<package namespace="/control/employee" 其他屬性忽略>


不過貌似不用

${pageContext.request.contextPath}也行.你試試

7. javaee 用struts2的文件上傳,保存才伺服器目錄下 伺服器是tomcat 為什麼電腦重啟後 文件就沒有了

首先,

文件上傳到伺服器是保存在磁碟上的,磁碟是永久性存儲介質,如果不是手動刪除或者中毒(這種可能性不大),是不會丟失的。你可能是上次運行的時候上傳的文件在伺服器中,後來被你重新發布項目把原項目直接覆蓋掉了,因為你原項目中可能沒有存你新發布的圖片,所以直接丟失掉了,建議如果有重要的上傳文件,先將已經上傳的文件備份一下,再發布新的項目。或者是你發布新文件的時候設置一下那個發布選項,只覆蓋舊文件,不要全部刪除後上傳新項目,如圖

8. java struts1的formbean中我定義了一個FormFile用來接收客戶端瀏覽器上傳上來的圖片,報下面錯,

form表單 添加enctyp=「。。。」,然後給上傳域 添加name屬性,後天接受name值,然後使用文件流上傳。

9. 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>

10. java 中如何向伺服器上傳圖片

我們使用一些已有的組件幫助我們實現這種上傳功能。
常用的上傳組件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload為例講解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然後只需要放置一個file控制項,並執行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代碼如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表單參數名:" + item.getFieldName() + ",表單參數值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上傳文件的大小:" + item.getSize());
System.out.println("上傳文件的類型:" + item.getContentType());
System.out.println("上傳文件的名稱:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上傳文件成功!");
}else{
request.setAttribute("upload.message", "沒有選擇上傳文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上傳文件失敗!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}

熱點內容
玩csol伺服器連接中斷怎麼辦 發布:2024-03-28 22:46:19 瀏覽:905
apk加密軟體 發布:2024-03-28 22:36:14 瀏覽:695
cpu不能直接訪問的存儲器 發布:2024-03-28 22:31:49 瀏覽:440
嘀嘀打車源碼 發布:2024-03-28 22:26:02 瀏覽:934
資料庫脆弱點 發布:2024-03-28 22:25:06 瀏覽:800
2021款es升級了哪些配置 發布:2024-03-28 21:26:44 瀏覽:384
下述調度演算法 發布:2024-03-28 21:22:24 瀏覽:616
捷達哪個配置裝有esp 發布:2024-03-28 21:17:41 瀏覽:196
天氣源碼 發布:2024-03-28 21:14:11 瀏覽:428
使命召喚紅魔浪潮如何配置 發布:2024-03-28 21:13:08 瀏覽:546