SSHフレームワークでファイルのアップロード機能を実現
3419 ワード
1.ページコードuploadをアップロードする.jsp
2.strutsの制御ジャンプのactionコードにより、選択したファイルをプロジェクトディレクトリの下のuploadフォルダにストリームでアップロードします.
2.strutsの制御ジャンプのactionコードにより、選択したファイルをプロジェクトディレクトリの下のuploadフォルダにストリームでアップロードします.
package com.boya.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class uploadAction extends ActionSupport {
//
private final static String UPLOADDIR = "/upload";
//
private List file;
//
private List fileFileName;
//
private List fileContentType;
public List getFile() {
return file;
}
public void setFile(List file) {
this.file = file;
}
public List getFileFileName() {
return fileFileName;
}
public void setFileFileName(List fileFileName) {
this.fileFileName = fileFileName;
}
public List getFileContentType() {
return fileContentType;
}
public void setFileContentType(List fileContentType) {
this.fileContentType = fileContentType;
}
public String execute() throws Exception {
System.out.println(this.getFileFileName());
for (int i = 0; i < file.size(); i++) {
//
uploadFile(i);
}
return "success";
}
//
private void uploadFile(int i) throws FileNotFoundException, IOException {
try {
InputStream in = new FileInputStream(file.get(i));
String dir = ServletActionContext.getRequest().getRealPath(UPLOADDIR);
File fileLocation = new File(dir);
//
if(!fileLocation.exists()){
boolean isCreated = fileLocation.mkdir();
if(!isCreated) {
// , , , 。
return;
}
}
String fileName=this.getFileFileName().get(i);
File uploadFile = new File(dir, fileName);
OutputStream out = new FileOutputStream(uploadFile);
byte[] buffer = new byte[1024 * 1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
} catch (FileNotFoundException ex) {
System.out.println(" !");
ex.printStackTrace();
} catch (IOException ex) {
System.out.println(" !");
ex.printStackTrace();
}
}
}