swfupload v2.2 或者2.5在struts1+spring+hibernate项目中 一开始的时候能上传文件,后来就不行了,让我很纳闷,网上也找了很多资料 ,但是没有提到我遇到的这个问题,
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
String path = request.getContextPath();
String jsessionid=request.getSession().getId();
%>
文件上传
上传状态栏
-----------------------------------------------------------------------------------------
strtus1 后台代码:
public ActionForward uploadAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// System.out.println("xxx");
SysFilesForm sysFilesForm = (SysFilesForm) form;
ISysFilesService sysFilesService = ServiceLoader.getSysFilesService();
try {
request.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
session.setAttribute("SESSIONID", session.getId());
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List> items = upload.parseRequest(request);
System.out.println("request:" + request.getParameter("PHPSESSID"));
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String now = df.format(date);
UserInfo user = (UserInfo) session.getAttribute(UserInfo.USERINFO);
Iterator> iter = items.iterator();
while (iter.hasNext()) {
System.out.println(" 进来了");
FileItem item = (FileItem) iter.next();
String fileNames = item.getName();
System.out.println(fileNames);
SysFiles sf = new SysFiles();
if (item.isFormField()) { // 判断是否为普通表单域,还是文件上传表单域。
/*
* String name = item.getFieldName(); String value =
* item.getString(); System.out.println("name = " + name);
* System.out.println("value = " + value);
* System.out.println("/r/n");
*/
} else {
String fieldName = item.getFieldName();
String fileName = item.getName();
System.out.println("文件类型 "
+ fileName.substring(fileName.lastIndexOf('.') + 1,
fileName.length()));
// boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
getListInSession(request).add(fileName);
getListInSession(request).add(UUID.randomUUID());
// String[] str=fieldName.split("\\.");
// int l=str.length-1;
// System.out.println("文件类型 "+str[l]);
//
System.out.println("fieldName = " + fieldName);
System.out.println("fileName = " + fileName);
// System.out.println("文件存储路径 "+request.getRealPath("/")+"uploadfile/");
// 路径 D:\Program
// Files\apache-tomcat-6.0.18\webapps\rockontrol_oa\UploadFiles\2009042991039312\
String filePath = this.getServlet().getServletContext()
.getRealPath("/")
+ "Files/";
File savePath = new File(filePath);
if (!savePath.exists()) { // 判断是否存在存放目录文件夹
savePath.mkdir();
savePath.createNewFile();
}
item.write(new File(filePath + now + "_" + fileName));
sf.setFilename(fileName);
sf.setFilepath("Files");
// 1mb=1024kb
// 1kb=1024byte(b)
long sizea = item.getSize(); // 上传文件大小
System.out.println("最初的文件大小: " + sizea);
double sizeb = new Double(sizea);
double sizec = sizeb / 1024 / 1024;
String parten = "#.#";
DecimalFormat decimal = new DecimalFormat(parten);
String str = decimal.format(sizeb / 1024 / 1024);
String size = String.valueOf((str)) + "MB";
if (sizec < 1) {
sf.setFilesize(sizea / 1024 + "KB");
} else {
sf.setFilesize(size);
}
System.out.println(item.getName());
// request.getRealPath("/")
// System.out.println("类型:------------"+request.getContentType());FileTypeJudge.getType
sf.setFiletype(FileTypeJudge.getType(
request.getRealPath("/") + "Files/" + now + "_"
+ fileName).toString());
sf.setNewfilename(now + "_" + fileName);
sf.setTime(new Date());
sf.setUploaduser(user.getYhdm());
int id = sysFilesService.save(sf);
if (id <= 0) {
System.out.println(fileName + "保存失败");
log.error(fileName + "保存失败");
} else {
System.out.println(fileName + "保存成功");
}
}
}
System.out.println("-------- final--------");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
// return findForwardCommon(mapping, form, "index");
}
public ActionForward getResult(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
List list = getListInSession(request);
request.getSession().removeAttribute("_result");
response.setCharacterEncoding("utf-8");
response.getWriter().print(list);
response.flushBuffer();
return null;
}
public List getListInSession(HttpServletRequest request) {
List result = (List) request.getSession().getAttribute("_result");
if (result == null) {
result = new ArrayList();
request.getSession().setAttribute("_result", result);
}
return result;
}
strtuts1 xml:
web.xml里涉及strtus1的:
网上看到struts2遇到这个问题的解决办法是过滤器里把/*改成 *.action
这个我这个虽然是strtus1但是我应该也没有哪里做了全路径拦截
解决办法:
把访问strustaction类改成访问servelt
不访问 strtus的action、
我的servelet是这样写的,当然里面有一些涉及数据库的操作 遇到同样问题的人只要参考文件操作的代码就好了
package com.sunland.servelet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import com.sunland.po.SysFiles;
import com.sunland.service.ISysFilesService;
import com.sunland.service.ServiceLoader;
import com.sunland.util.FileTypeJudge;
import com.sunland.util.UserInfo;
public class UploadFile extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public UploadFile() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
ISysFilesService sysFilesService = ServiceLoader.getSysFilesService();
HttpSession session = request.getSession();
session.setAttribute("SESSIONID", session.getId());
UserInfo user = (UserInfo) session.getAttribute(UserInfo.USERINFO);
session.setAttribute("SESSIONID", session.getId());
FileItemFactory factory = new DefaultFileItemFactory();
FileUpload upload = new FileUpload(factory);
Iterator items;
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String now = df.format(date);
try {
items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem item = (FileItem) items.next();
if (!item.isFormField()) {
String name = item.getName();
String filetype = name.substring(name.lastIndexOf("."));
//String name = System.currentTimeMillis()+filetype;
// System.out.println(name+"--"+new String(name.getBytes("GBK"),"UTF-8"));
String realpath = request.getRealPath("/Files");
String path = realpath + File.separatorChar +now + "_" + name;
File file = new File(path);
if (!file.exists()) {
File file1 = new File(realpath);
file1.mkdirs();
file.createNewFile();
}else{
file.createNewFile();
}
item.write(file);
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
out.print("上传的文件为:" + name + "
");
out.print("保存的地址为:" + path + "");
SysFiles sf = new SysFiles();
sf.setFilename(name);
sf.setFilepath("Files");
// 1mb=1024kb
// 1kb=1024byte(b)
long sizea = item.getSize(); // 上传文件大小
System.out.println("最初的文件大小: " + sizea);
double sizeb = new Double(sizea);
double sizec = sizeb / 1024 / 1024;
String parten = "#.#";
DecimalFormat decimal = new DecimalFormat(parten);
String str = decimal.format(sizeb / 1024 / 1024);
String size = String.valueOf((str)) + "MB";
if (sizec < 1) {
sf.setFilesize(sizea / 1024 + "KB");
} else {
sf.setFilesize(size);
}
System.out.println(item.getName());
// request.getRealPath("/")
// System.out.println("类型:------------"+request.getContentType());FileTypeJudge.getType
sf.setFiletype(FileTypeJudge.getType(
request.getRealPath("/") + "Files/" + now + "_"
+ name).toString());
sf.setNewfilename(now + "_" + name);
sf.setTime(new Date());
sf.setUploaduser(user.getYhdm());
int id = sysFilesService.save(sf);
if (id <= 0) {
System.out.println(name + "保存失败");
//log.error(name + "保存失败");
} else {
System.out.println(name + "保存成功");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public void init() throws ServletException {
}
}
servlet的web.xml配置 很简单
这样swfupload的就可以上传了 另外我改了几个 官网的php例子,可以上传批量文件,文件名称是swfobjectdemo,里面的改了可以上传,其他的没改道理一样把upload.php拷贝过去就好了,官网下载下来的是没有保存文件的,有兴趣的朋友可以下载学习。版本是最新的swfupload v2.5
另外这里放了一个 纯servlet上的例子 这是网上找的,你们可以参考