java action上传文件_java实现文件上传
在Java中,要實現(xiàn)文件上傳,可以有兩種方式:
1、通過Servlet類上傳
2、通過Struts框架實現(xiàn)上傳
這兩種方式的根本還是通過Servlet進行IO流的操作。
一、通過Servlet類上傳
1、編寫Sevlet類
這里用純Servlet實現(xiàn)的時候,無法獲取文件的文件名以及一些其他信息。還不知道怎么解決。
2、配置web.xml文件
添加以下代碼:
1
2
3 fileUploadServlet
4 com.chanshuyi.upload.FileUploadServlet
5
6
7 fileUploadServlet
8 /fileUploadServlet
9
3、前臺代碼
1
通過Servlet實現(xiàn)上傳
2
二、通過Struts框架實現(xiàn)上傳
1、配置struts.xml文件
添加如下Action:
2、編寫Action類
1 package com.chanshuyi.upload;
2
3 import java.io.File;
4
5 import javax.servlet.ServletContext;
6 import javax.servlet.http.HttpServletResponse;
7
8 import org.apache.commons.io.FileUtils;
9 import org.apache.struts2.ServletActionContext;
10
11 import com.opensymphony.xwork2.ActionSupport;
12
13 @SuppressWarnings("serial")
14 public class FileUploadAction extends ActionSupport {
15
16 /** ActionContext對象 **/
17 ServletContext servletContext = ServletActionContext.getServletContext();
18
19 HttpServletResponse response = ServletActionContext.getResponse();
20
21 /* 特定的命名規(guī)則,不能改變 */
22 /** 上傳的文件,名字要與前臺name屬性相同 **/
23 private File file;
24
25 /** 上傳文件名稱 **/
26 private String fileFileName;
27
28 /** 上傳文件類型 **/
29 private String fileContentType;
30
31 public String execute()throws Exception
32 {
33 if(file == null)
34 {
35 return null;
36 }
37 /* 設置文件保存地址 */
38 File saveFile = new File(servletContext.getRealPath("/uploaded"), fileFileName);
39 System.out.println("[文件保存地址]:" + saveFile.getAbsolutePath());
40 if(!saveFile.getParentFile().exists())
41 {
42 saveFile.getParentFile().mkdir();
43 }
44
45 FileUtils.copyFile(file, saveFile);
46 System.out.println("[系統(tǒng)消息]:文件已經保存,保存路徑為->" + saveFile.getAbsolutePath());
47
48 response.getWriter().write("");
49
50 return null;
51 }
52 /* 省略GET/SET方法 */
53 }
3、前臺頁面
本例寫的Action處理后不返回result,直接向response對象寫入數(shù)據(jù),彈出上傳成功的提示。
總結
以上是生活随笔為你收集整理的java action上传文件_java实现文件上传的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 薄荷煲鸡的功效与作用、禁忌和食用方法
- 下一篇: 铁皮石斛花茶的功效与作用、禁忌和食用方法