ssh專案中的檔案上傳
阿新 • • 發佈:2019-01-24
上傳檔案要新增兩個jar包commonse,在pom中新增
<!--檔案上傳,新增這個就直接幫助我們自動新增其他所需的依賴-->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.5</version>
</dependency>
<!--javax 獲取檔案路徑的時候使用-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
頁面中的配置,要使用post方式提交,新增屬性enctype="multipart/form-data"
<form method="post" action="/fileUpload.action" enctype="multipart/form-data" >
<input name="user" />
<input name="pass"/>
<input type="file" name="file"/>
<button type="submit">提交</button>
</form>
在action中的配置,新增三個屬性,這三個屬性必須要建立,否則會報錯.當然不要忘記set/get方法
public File file;//io包中的file
public String fileFileName;//接收到的檔案的名字
public String fileContentType;//接收到的檔案的型別
上傳檔案的方法如下
@Action(value = "/fileUpload" ,results = {@Result(name = "success" ,location = "/seccess.jsp",type = "redirect")})
public String fileUpload() throws IOException {
//獲得輸入流,讀取檔案的內容
FileInputStream fileInputStream=new FileInputStream(file);
byte[] b=new byte[102400];
fileInputStream.read(b);
//獲取專案系統路徑
HttpServletRequest request = ServletActionContext.getRequest();
//獲取檔案的路徑
String path=request.getServletContext().getRealPath(fileFileName);
//獲取最後一個斜槓的位置
int weizhi = path.lastIndexOf("\\");
//將檔案的路徑進行改寫
String newPath = path.substring(0, weizhi);
File newFile=new File(newPath+"\\file\\"+fileFileName);
//將檔案寫入上面定義的資料夾中
FileOutputStream fileOutputStream=new FileOutputStream(newFile);
fileOutputStream.write(b);
fileInputStream.close();
fileOutputStream.close();
return "success";
}