67,513
社区成员
发帖
与我相关
我的任务
分享
public String execute() throws Exception{
//取得需要上传的文件数组
File[] files = getUpload();
//遍历每个需要上传的文件
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
//以服务器的文件保存地址和源文件名建立上传文件输出流
FileOutputStream fos = new FileOutputStream(getSavePath()+"\\"+getUploadFileName()[i]);
//以每个需要上传的文件建立输入流
FileInputStream fis = new FileInputStream(files[i]);
//将每个需要上传的文件写入
byte[] buffer = new byte[1024];
int length = 0;
while ((length=fis.read(buffer))>0) {
fos.write(buffer,0,length);
}
fos.close();
}
return SUCCESS;
}
<package name="mystruts" extends="struts-default">
<action name="upload" class="com.app.action.UploadAction">
<!-- 动态设置Action的savePath属性 -->
<param name="savePath">/upload</param>
<!-- 配置文件上传的拦截器 -->
<interceptor-ref name="fileUpload">
<!-- 配置允许上传的文件类型 -->
<param name="allowedTypes">image/png,image/gif,image/jpeg</param>
<param name="maximumSize">20480000</param>
</interceptor-ref>
<!-- 配置系统默认的拦截器 -->
<interceptor-ref name="defaultStack"></interceptor-ref>
<result name="success">/success.jsp</result>
<result name="input">/upload.jsp</result>
</action>
</package>
String root = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/upload");
FileOutputStream fos = new FileOutputStream(root+"\\"+getUploadFileName()[i]);
private File[] files;
private File[] fileFileName;
private File[] fileContentType;
//getters && setters
public String execute() throws Exception {
for (int i = 0; i < files.length; i++) {
//...
String root = ServletActionContext.getRequest().getSession()
.getServletContext().getRealPath("/upload");
//加点东西 保证目录: %deployPath%+"/upload" 存在
File destFile = new File(root, fileFileName.get(i));
//...
}
if (files != null && files.length > 0) {
List<File> acceptedFiles = new ArrayList<File>(files.length);
List<String> acceptedContentTypes = new ArrayList<String>(files.length);
List<String> acceptedFileNames = new ArrayList<String>(files.length);
String contentTypeName = inputName + "ContentType";
String fileNameName = inputName + "FileName";
for (int index = 0; index < files.length; index++) {
if (acceptFile(action, files[index], fileName[index], contentType[index], inputName, validation, ac.getLocale())) {
acceptedFiles.add(files[index]);
acceptedContentTypes.add(contentType[index]);
acceptedFileNames.add(fileName[index]);
}
}
if (!acceptedFiles.isEmpty()) {
Map<String, Object> params = ac.getParameters();
params.put(inputName, acceptedFiles.toArray(new File[acceptedFiles.size()]));
params.put(contentTypeName, acceptedContentTypes.toArray(new String[acceptedContentTypes.size()]));
params.put(fileNameName, acceptedFileNames.toArray(new String[acceptedFileNames.size()]));
}
}