81,094
社区成员
发帖
与我相关
我的任务
分享
<action name="savecompany" class="companyAction"
method="saveCompany">
<!-- Struts2内置的文件上传拦截器 -->
<interceptor-ref name="fileUpload">
<param name="allowedTypes">
image/bmp,image/gif,image/JPEG,image/pjpeg,image/jpg
</param>
<param name="maximumSize">2048000</param>
</interceptor-ref>
<interceptor-ref name="defaultStack" />
<result name="success">/operations.jsp</result>
</action>
public String saveCompany() {
System.out.println("upload file");
// upload file
HttpServletRequest request = ServletActionContext.getRequest();
// Get real path
String realpath = request.getSession().getServletContext().getRealPath(
"/");
//save path is a directory
String savepath = realpath + "images\\" + this.getId();
String filetype = this.getLogoContentType();
//create file type
filetype = filetype.replace("image/", "");
filetype = filetype.replace("pjpeg", "jpg");
try {
if (CreatePath(savepath) == false) {
throw new SystemException("创建文件夹失败,");
} else {
//file = save path + logo. + file type
String savefile = savepath + "\\" + "logo." + filetype;
File tarFile = new File(savefile);
System.out.println(savefile);
fu.uploadFile(this.getLogo(), tarFile);
}
} catch (Exception e) {
throw new SystemException("文件上传失败,");
}
return SUCCESS;
}
package com.prodinfo.common;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import com.opensymphony.xwork2.ActionSupport;
public class FileUpload extends ActionSupport implements IFileUpload {
private static final int BUFFER_SIZE = 2048000;
public String uploadFile(File src, File target) {
try {
FileOutputStream fileout = new FileOutputStream(target);
FileInputStream filein = new FileInputStream(src);
byte[] buffer = new byte[BUFFER_SIZE];
int len = 0;
while ((len = filein.read(buffer)) > 0) {
fileout.write(buffer, 0, len);
}
fileout.close();
filein.close();
} catch (Exception e) {
throw new SystemException("文件上传失败,");
}
return SUCCESS;
}
}