1. 程式人生 > >struts2之單文件上傳(7)

struts2之單文件上傳(7)

multipart 讀取 ret ipa filename ons private .get lose

前臺頁面jsp

<form action="uploadAction" enctype="multipart/form-data" method="post">
<label>上傳文件:</label>
<input type="file" name="myfile"/>
<input type="submit" value="提交"/>
</form>

action

public class UploadAction extends ActionSupport {
//三個全局屬性註意命名規則,屬性名的前半部分保持一致,不然報空值
//上傳的文件(舊文件)
private File myfile;
//上傳的文件名(舊文件)
private String myfileFileName;
//上傳文件類型(舊文件)
private String myfileFileContentType;


//處理上傳請求
public String upload(){
//生成新的文件名(使用uuid)
String newmyfilename = UUIDUtil.getUUID()+myfileFileName.substring(myfileFileName.lastIndexOf("."));
//指定上傳的位置
String path = ServletActionContext.getServletContext().getRealPath("upload");
//上傳文件的位置
String filepath = path+File.pathSeparator+newmyfilename;
System.out.println("filepath = "+filepath);
//構建新文件
File newfile = new File(filepath);

//讀入寫出 從舊文件讀內容到新文件
FileInputStream fis = null;
FileOutputStream fos = null;

try {
//將舊文件封裝到輸入流
fis = new FileInputStream(myfile);
//將新文件封裝到輸出流
fos = new FileOutputStream(newfile);
//設置一個字節數組緩沖內容
byte [] bt = new byte[1024];
int len = 0;
/**
* 循環讀取緩沖區的內容
* 輸入流不斷的將字節讀入到緩沖區(舊文件到緩沖區)
* 輸出流不斷的將字節寫出到新文件(緩沖區到新文件)
*/
while((len = fis.read(bt))!=-1){
fos.write(bt, 0, len);
}
fos.close();
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


return SUCCESS;
}


public File getMyfile() {
return myfile;
}


public void setMyfile(File myfile) {
this.myfile = myfile;
}

public String getMyfileFileContentType() {
return myfileFileContentType;
}


public void setMyfileFileContentType(String myfileFileContentType) {
this.myfileFileContentType = myfileFileContentType;
}


public String getMyfileFileName() {
return myfileFileName;
}


public void setMyfileFileName(String myfileFileName) {
this.myfileFileName = myfileFileName;
}




}

struts.xml

<!-- struts2中文件上傳攔截
struts2 的核心包下的default.properties文件裏有默認的大小為struts.multipart.maxSize=2097152,也就是2M. 這是struts2默認攔截,
解決方法:在struts.xml配置文件中,添加
<constant name="struts.multipart.maxSize" value="10485760"/>
這裏的value單位為B,即10485760B = 10MB。
-->
<constant name="struts.multipart.maxSize" value="10485760"/>
<package name="upload" namespace="/" extends="struts-default">
<action name="uploadAction" class="com.oak.action.UploadAction" method="upload">
<result>
/welcome.jsp
</result>
</action>
</package>

struts2之單文件上傳(7)