1.在jsp文件中進(jìn)行定義
1
2
3
4
5
|
< form action = "/StrutsFileUpAndDown/register.do" method = "post" enctype = "multipart/form-data" > 名字:< input type = "text" name = "name" /> 頭像:< input type = "file" name = "file" /> < input type = "submit" value = "注冊(cè)用戶" > </ form > |
2.在Form表單中定義FormFile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.yourcompany.struts.form; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.upload.FormFile; /** * MyEclipse Struts * Creation date: 08-24-2017 * * XDoclet definition: * @struts.form name="userForm" */ public class UserForm extends ActionForm { /* * Generated Methods */ private String username; private FormFile file; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public FormFile getFile() { return file; } public void setFile(FormFile file) { this.file = file; } } |
3.利用struts文件進(jìn)行關(guān)聯(lián)Form,關(guān)聯(lián)以后
1)利用表單實(shí)例進(jìn)行獲取FormFile實(shí)例,在獲取以后,我們可以通過(guò)FormFile獲取上傳文件的各種信息
1
2
3
4
5
6
7
8
9
|
UserForm userForm = (UserForm) form; String username = userForm.getUsername(); FormFile file = userForm.getFile(); //通過(guò)formFile可以獲取關(guān)于用戶上傳文件的各種信息 //用于獲取文件名字 String fileName = file.getFileName(); //用于獲取文件大小 int fileSize = file.getFileSize(); |
2)通過(guò)FormFile實(shí)例獲取輸入流,創(chuàng)建一個(gè)輸出流,并且在代碼中獲取tomcat服務(wù)器的絕對(duì)路徑
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
|
try { //獲取輸入流 is = file.getInputStream(); //得到輸出流 //1.得到file文件夾,上傳到tomcat服務(wù)器后的絕對(duì)路徑(file文件為新創(chuàng)建的文件夾) String filePath = this.getServlet().getServletContext().getRealPath("/file"); //兩個(gè)"//"的其中一個(gè)"/"為轉(zhuǎn)義符 os=new FileOutputStream(filePath+"\\"+fileName); int len=0;//表示讀取的字節(jié) //做一個(gè)緩存,防止文件過(guò)大而造成錯(cuò)誤 byte[] buff=new byte[1024]; while((len=is.read(buff))!=-1) { os.write(buff,0,len); } is.close(); os.close(); } |
以上這篇基于Struts文件上傳(FormFile)詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/callyblog/archive/2017/08/24/7425138.html