2012-03-22 10:36:02.0|分类: struts|浏览量: 1685
做项目是需要将本地图片上传到服务器,可是tiny_mce自带的image插件不能很好的实现, tiny_mce需要动的输入图片地址,这个地址还得是服务器上的地址。所以不满足需要,需要改进。 通常的办法就是使用ajax把图片提交到服务器,然后返回图片在服务器上的地址,然后再把返回的地址写到地址栏里,这就ok了。 下面给出我写的代码: 如果你不懂ajaxfileupload请看http://www.phpletter.com/Our-Projects/AjaxFileUpload/ jsp页面:需要引入jquery.js 和ajaxfileupload.js,注意jquery.js需要放在前面,如果放在后面的话,不会执行下面的方法。 <script type="text/javascript" src="../../../js/jquery.js"></script> <script type="text/javascript" src="../../utils/ajaxfileupload.js"></script>
<script type="text/javascript"> function uploadFiles() { $.ajaxFileUpload({ url:'http://localhost:8080/fangdo/admin/uploadPhoto.action', secureuri:false, fileElementId:'file', dataType: 'json', success: function (result, statu) { if (result.status == 'success'){ $("#src").val(result.src); ImageDialog.showPreviewImage(result.src); }else { alert(result.status); } }, error: function (result, status, e) { alert(e); } }) } </script>
<tr> <td><a href="#" onClick="uploadFiles();"><script>document.write('\文件上传')</script></a></td> <td><input style="WIDTH: 250" id="file" name="file" type="file"></td> </tr> action中的方法: // photo upload
public void uploadPhoto() throws ActionException {
String realDir = getSession().getServletContext().getRealPath("");
HttpServletRequest request = ServletActionContext.getRequest();
String contextpath = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName()
+ ":" + request.getServerPort() + contextpath + "/";
String status = "error";
try {
String filePath = "uploads";
String imagePath = "image" ;
String realPath = realDir + "\\" + filePath+"\\"+imagePath;
// 判断路径是否存在,不存在则创建
File dir = new File(realPath);
if (!dir.isDirectory())
dir.mkdir();
//// Check that we have a file upload request
if (ServletFileUpload.isMultipartContent(request)) {//为什么要判断看后面注 DiskFileItemFactory dff = new DiskFileItemFactory();
dff.setRepository(dir);
dff.setSizeThreshold(1024000);
//// Create a new file upload handler
ServletFileUpload servletFileUpload = new ServletFileUpload(dff);
FileItemIterator fileItemIterator = null;
// Parse the request
servletFileUpload.setHeaderEncoding("UTF-8"); // 设置编码,因为我的jsp页面的编码是utf-8的
fileItemIterator = servletFileUpload.getItemIterator(request);
String tilte = "";// 标题
String url = "";
String fileName = "";
String realFileName = "";
while (fileItemIterator.hasNext()) {
FileItemStream fis = fileItemIterator.next();
try {
if (!fis.isFormField() && fis.getName().length() > 0) {
fileName = fis.getName();
Pattern reg = Pattern.compile("[.]jpg|png|jpeg|gif$");
Matcher matcher = reg.matcher(fileName);
if (!matcher.find()) {
status = "文件格式不对";
break;
}
realFileName = new Date().getTime()
+ fileName.substring(
fileName.lastIndexOf("."),
fileName.length());
url = realPath + "\\" + realFileName;
BufferedInputStream in = new BufferedInputStream(fis.openStream());
FileOutputStream fous = new FileOutputStream(new File(url));
BufferedOutputStream out = new BufferedOutputStream(fous);
Streams.copy(in, out, true);
status="success";
} /*else {
String fname = fis.getFieldName();
if (fname.indexOf("pictitle") != -1) {
BufferedInputStream in = new BufferedInputStream(fis.openStream());
byte c[] = new byte[10];
int n = 0;
while ((n = in.read()) != -1) {
tilte = new String(c, 0, n);
break;
}
}
}
*/
} catch (IOException e) {
e.printStackTrace();
}
}
HttpServletResponse respone = ServletActionContext.getResponse();
respone.setContentType("text/html");
respone.setCharacterEncoding("UTF-8");
respone.setStatus(200);
String retxt = "{src:'" + contextpath +"/"+ filePath + "/"+imagePath+"/"
+ realFileName + "',status:'"+status+"'}";
respone.getWriter().print(retxt);
}
} catch (Exception e) {
e.printStackTrace();
}
}
配置文件: <action name="uploadPhoto" class="com.fangdo.action.CmsTitleAction" method="uploadPhoto"> </action> 注:1、检查request是否是一个上传请求 // Check that we have a file upload request boolean isMultipart = ServletFileUpload.isMultipartContent(request);
静态方法isMultipartContent代码:就是判断contentType是否是multipart/ 这就是为什么form类型要设成multipart/form-data吧 public static final boolean isMultipartContent( HttpServletRequest request) { if (!"post".equals(request.getMethod().toLowerCase())) { return false; } String contentType = request.getContentType(); if (contentType == null) { return false; } if (contentType.toLowerCase().startsWith(MULTIPART)) { return true; } return false; } public static final String MULTIPART = "multipart/";
|