Struts2文件上傳依賴fileupload.jar實現

1.struts2-core.jar中的org.apache.struts2包下面有個default.properties文件,文件中記錄了默認的配置:

比如:

struts.multipart.maxSize=2097152     默認支持上傳文件的最大字節

struts.multipart.saveDir=    上傳文件的默認臨時文件目錄,默認爲null

struts.i18n.encoding=UTF-8    默認編碼方式

這些默認的設置都可以通過在struts.xml文件中通過<constant>標籤更改

2. 查看FileUploadInterceptor.java可以看到,上傳文件時,會默認注入2個參數,分別爲*ContentType和*FileName,分別記錄內容類型和文件名稱

在action中定義相應的屬性名稱,並且提供get和set方法就能得到相應的值

  <body>
  	<s:form action="upload" theme="simple" method="post" enctype="multipart/form-data">
  		username:<s:textfield name="username"/><br>
  		password:<s:textfield name="password"/><br>
  		file:<s:file name="file"/><br>
  		<s:submit value="submit"/>
  	</s:form>
  </body>

package cn.com.baiwen.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {

	private String username;

	private String password;

	private File file;

	private String fileFileName;

	private String fileContentType;

	@Override
	public String execute() throws Exception {

		InputStream is = new FileInputStream(file);

		String path = ServletActionContext.getServletContext().getRealPath("/upload");

		File targetFile = new File(path, fileFileName);

		OutputStream os = new FileOutputStream(targetFile);

		byte[] buffer = new byte[400];

		int length = 0;

		while ((length = is.read(buffer)) > 0) {
			os.write(buffer,0,length);
		}

		is.close();

		os.close();

		return SUCCESS;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	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;
	}

}

  <body>
  	usrename:<s:property value="username"/><br>
  	pasword:<s:property value="password"/><br>
  	file:<s:property value="fileFileName"/>
  </body>

<struts>

	<!-- 定義默認設置 -->
	<constant name="struts.multipart.saveDir" value="c:/"></constant>

	<package name="struts" extends="struts-default">
		<action name="upload" class="cn.com.baiwen.action.UploadAction">
			<result name="success">/upload/uploadResult.jsp</result>
		</action>
	</package>
	
</struts>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章