1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package com.gisgraphy.webapp.action;
24
25 import java.io.File;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30
31 import org.apache.struts2.ServletActionContext;
32
33 import com.gisgraphy.Constants;
34
35
36
37
38 public class FileUploadAction extends BaseAction {
39 private static final long serialVersionUID = -9208910183310010569L;
40
41 private File file;
42
43 private String fileContentType;
44
45 private String fileFileName;
46
47 private String name;
48
49
50
51
52
53
54
55
56 public String upload() throws Exception {
57 if (this.cancel != null) {
58 return "cancel";
59 }
60
61
62 String uploadDir = ServletActionContext.getServletContext()
63 .getRealPath("/resources")
64 + "/" + getRequest().getRemoteUser() + "/";
65
66
67 File dirPath = new File(uploadDir);
68
69 if (!dirPath.exists()) {
70 dirPath.mkdirs();
71 }
72
73
74 InputStream stream = new FileInputStream(file);
75
76
77 OutputStream bos = new FileOutputStream(uploadDir + fileFileName);
78 int bytesRead;
79 byte[] buffer = new byte[8192];
80
81 while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
82 bos.write(buffer, 0, bytesRead);
83 }
84
85 bos.close();
86 stream.close();
87
88
89 getRequest().setAttribute("location",
90 dirPath.getAbsolutePath() + Constants.FILE_SEP + fileFileName);
91
92 String link = getRequest().getContextPath() + "/resources" + "/"
93 + getRequest().getRemoteUser() + "/";
94
95 getRequest().setAttribute("link", link + fileFileName);
96
97 return SUCCESS;
98 }
99
100
101
102
103
104
105 @Override
106 public String execute() {
107 return INPUT;
108 }
109
110 public void setFile(File file) {
111 this.file = file;
112 }
113
114 public void setFileContentType(String fileContentType) {
115 this.fileContentType = fileContentType;
116 }
117
118 public void setFileFileName(String fileFileName) {
119 this.fileFileName = fileFileName;
120 }
121
122 public void setName(String name) {
123 this.name = name;
124 }
125
126 public String getName() {
127 return name;
128 }
129
130 public File getFile() {
131 return file;
132 }
133
134 public String getFileContentType() {
135 return fileContentType;
136 }
137
138 public String getFileFileName() {
139 return fileFileName;
140 }
141
142 @Override
143 public void validate() {
144 if (getRequest().getMethod().equalsIgnoreCase("post")) {
145 getFieldErrors().clear();
146 if ("".equals(fileFileName) || file == null) {
147 super.addFieldError("file", getText("errors.requiredField",
148 new String[] { getText("uploadForm.file") }));
149 } else if (file.length() > 2097152) {
150 addActionError(getText("maxLengthExceeded"));
151 }
152 }
153 }
154 }