以下是基本上借鉴别人的代码,只是稍微完善一下
UploadImgAction.java
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.json.simple.JSONObject;
import yanwo.web.util.Utils;
/**
*
* @author pengmaokui
*/
public class UploadImgAction extends ActionSupport{
private final long MAX_SIZE = 2*1024*1024;
Log log = LogFactory.getLog(this.getClass());
private File imgFile; //页面传过来的数据 以下都是
private String imgFileFileName;
private String imgWidth;
private String imgHeight;
private String align;
private String imgTitle;
public void setImgFile(File imgFile) {
this.imgFile = imgFile;
}
public void setImgFileFileName(String imgFileFileName) {
this.imgFileFileName = imgFileFileName;
}
public void setImgWidth(String imgWidth) {
this.imgWidth = imgWidth;
}
public void setImgHeight(String imgHeight) {
this.imgHeight = imgHeight;
}
public void setAlign(String align) {
this.align = align;
}
public void setImgTitle(String imgTitle) {
this.imgTitle = imgTitle;
}
public String uploadImg() {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html; charset=UTF-8");
// 文件保存目录路径
String savePath = ServletActionContext.getServletContext().getRealPath("/") + "Content/news/";
// 文件保存目录URL
String saveUrl = request.getContextPath() + "/Content/news/";
// 定义允许上传的文件扩展名
String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };
// 最大文件大小
long maxSize = MAX_SIZE;
PrintWriter out = null;
try {
out = response.getWriter();
} catch (IOException e1) {
log.error(e1);
}
if (imgFile == null) {
out.println(getError("请选择文件。"));
return null;
}
// 检查目录
File uploadDir = new File(savePath);
if (!uploadDir.isDirectory()) {
out.println(getError("上传目录不存在。"));
return null;
}
// 检查目录写权限
if (!uploadDir.canWrite()) {
out.println(getError("上传目录没有写权限。"));
return null;
}
// 创建文件夹
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String ymd = sdf.format(new Date());
savePath += ymd + "/";
saveUrl += ymd + "/";
File dirFile = new File(savePath);
if (!dirFile.exists()) {
dirFile.mkdirs();
}
String fileExt = imgFileFileName.substring(imgFileFileName.lastIndexOf(".") + 1).toLowerCase();
if (!Arrays.<String> asList(fileTypes).contains(fileExt)) {
out.println(getError("上传文件扩展名[" + fileExt + "]是不允许的扩展名。"));
return null;
}
if (imgFile.length() > maxSize) {
out.println(getError("[ " + imgFileFileName + " ]超过单个文件大小限制,文件大小[ " + imgFile.length() + " ],限制为[ " + maxSize + " ] "));
return null;
}
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;
File uploadedFile = new File(savePath, newFileName);
try {
Utils.copy(imgFile, uploadedFile);
JSONObject obj = new JSONObject();
obj.put("error", 0);
obj.put("url", saveUrl + newFileName);
log.debug(obj);
out.println(obj.toString());
log.debug("上传图片:[" + uploadedFile.getName() + "]" + ">>>[" + newFileName + "]成功");
} catch (Exception e) {
log.error("图片上传失败:" + e);
}
return null;
}
private String getError(String message) {
JSONObject obj = new JSONObject();
obj.put("error", 1);
obj.put("message", message);
log.debug(obj);
return obj.toString();
}
}
copy(Filesrc,File dst);
public static void copy(File src, File dst) {
try {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE);
byte[] buffer = new byte[BUFFER_SIZE];
while (in.read(buffer) > 0) {
out.write(buffer);
}
} finally {
if (null != in) {
in.close();
}
if (null != out) {
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
struts.xml
<action name="uploadImg" class="yanwo.web.manage.action.UploadImgAction" method="uploadImg">
</action>
jsp
options = {
uploadJson : './uploadImg.do',
fileManagerJson : '../editor/jsp/file_manager_json.jsp',
allowFileManager : true,
items : [
'source', '|', 'undo', 'redo', '|', 'preview', 'cut', 'copy', 'paste',
'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '|',
'formatblock', 'fontname', 'fontsize', '/', 'forecolor', 'hilitecolor', 'bold',
'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
'link', 'unlink', '|', 'about']
}
KindEditor.ready(function(K) {
window.editor = K.create('#editor_id',options);
});
</script>