会先显示上传成功的界面,然后就报这个异常,文件上传 失败。
空指针报的是文件输出流。,谁帮我解决了,再加50分,,弄了好久了。
这个是浏览器上报的错。。,我发现了,action里面的execute方法竟然会执行两遍,,我写了个输出语句System.out.println(fileName);第一次是test.txt,第二次是null,,.找不到原因会执行两遍。
空指针报的是文件输出流。,谁帮我解决了,再加50分,,弄了好久了。
这个是浏览器上报的错。。,我发现了,action里面的execute方法竟然会执行两遍,,我写了个输出语句System.out.println(fileName);第一次是test.txt,第二次是null,,.找不到原因会执行两遍。
解决方案 »
- spring基于注解的事务管理配置 注解不起作用
- 介绍JAVA中的Collection FrameWork(包括如何写自己的数据结构)?
- java开发了个网站问题不断
- 我想请有经验的朋友,谈论一下OA系统中的工作流的定义和处理方法!谢谢。
- Hibernate中多对多的问题
- 安装tomcat总是安装不了
- 在windows操作系統上開發Java程序需要安裝哪些軟件?
- soap软件包里有什么内容,到哪下载呀?
- 请问大家是如何解决jbuilder8里面的“字符移位现象”的?即插入或删除的字符并不在光标显示处???好烦恼呀!!!
- 用jcreator开发j2ee合适吗,应该如何设置?
- 求概率分布抽奖函数的方法
- java 链接数据库
public class FileUpload extends ActionSupport{ /**
*
*/
private static final long serialVersionUID = 1L;
private File upfile=null; //上传文件信息
private String upfileFileName=null;//上传文件的名字
private String upfileContentType=null;//文件的类型
private String savePath=null;//保存的路径 public String getSavePath(){
return ServletActionContext.getServletContext().getRealPath(savePath);
}
public File getUpfile() {
return upfile;
}
public void setUpfile(File upfile) {
this.upfile = upfile;
}
public String getUpfileFileName() {
return upfileFileName;
}
public void setUpfileFileName(String upfileFileName) {
this.upfileFileName = upfileFileName;
}
public String getUpfileContentType() {
return upfileContentType;
}
public void setUpfileContentType(String upfileContentType) {
this.upfileContentType = upfileContentType;
}
public void setSavePath(String savePath) {
this.savePath = savePath;
}
public String execute1(){
try {
FileOutputStream out=new FileOutputStream(getSavePath()+"\\"+upfileFileName);
System.out.println(upfileFileName);
FileInputStream in=new FileInputStream(upfile);
byte[] buffer=new byte[1024];
int len=0;
while((len=in.read(buffer))!=-1){
out.write(buffer,0,len);
} } catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e){
e.printStackTrace();
}
return "success";
}
}
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd"><struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />
<constant name="struts.multipart.parser" value="jakarta" />
<constant name="struts.multipart.saveDir" value="/tmp"></constant>
<constant name="struts.multipart.maxSize" value="5024000" />
<package name="default" namespace="/" extends="struts-default">
<!-- <default-action-ref name="index" />
<global-results>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="error"/>
</global-exception-mappings>
-->
<action name="index" class="cn.nit.fileupload.action.LoginAction">
<result name="index">
/index.jsp
</result>
</action>
<action name="fileUpload" class="cn.nit.fileupload.action.FileUpload" method="execute1" >
<interceptor-ref name="defaultStack"></interceptor-ref>
<interceptor-ref name="fileUpload">
<param name="maximumSize">4096000</param>
<param name="allowedTypes">text/plain</param>
</interceptor-ref> <param name="savePath">/save</param>
<result name="success">
/success.jsp
</result>
<result name="input">
/index.jsp
</result>
</action>
</package>
</struts>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title> </head>
<body> <form action="fileUpload" enctype="multipart/form-data" method="post">
<input name="upfile" type="file"/><br/>
<input type="submit" value="上传" />
</form>
</body>
<s:debug></s:debug>
</html>
JSP
<div id="fileId" style='display:none;' class="file-box">
<form id="form2" method="post" enctype="multipart/form-data">
<input type='text' name='textfield' id='textfield' class='txt' />
<input type='button' class='btn' value='浏览...' />
<input type="file" name="myfile" class="file" id="myfile"
size="28" onchange="document.getElementById('textfield').value=this.value" />
<input type="button" name="button" class="btn" id="btnSubmit" onclick="uploadExcel()" value="上传" />
</form>
</div>
JS
function uploadExcel() {
var fileValue = document.getElementById("myfile").value;
var length=fileValue.length;
var xls = fileValue.substring(length-3,length);
if(fileValue != ""){
if(xls != "xls"){
alert("请选择正确的文件格式:如(test.xls)");
var obj = document.getElementById('myfile') ;
obj.outerHTML=obj.outerHTML;
document.getElementById("textfield").value = "";
} else {
$(document).ready(function() {
var options = {
url : getRootPath()+"/report/Upload.action",
type : "POST",//提交方式
dataType : "script",//数据类型
success : function(msg) {//调用Action后返回过来的数据
alert("文件上传成功");
$("#search").hide();
$("#gridShow").show();
loadDimensionsTable(5);
var obj = document.getElementById('myfile') ;
obj.outerHTML=obj.outerHTML;
document.getElementById("textfield").value = "";
}
};
$("#form2").ajaxSubmit(options);//绑定页面中form表单的id
return false;
});
}
} else {
alert('请选择上传文件!');
}
}
Action
public String upload() throws Exception {
System.out.println("新导入");
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
response.setContentType("text/html;charset=utf-8");
response.setCharacterEncoding("utf-8");
HttpSession session = request.getSession();
SysUser su = (SysUser) session.getAttribute("sysUser");
int userId = su.getUserId(); System.out.println("处理文件.....");
String values = "";
String key = "";
// 连接数据库查询并返回结果
Connection conn = DBConnection.getConnection();
PreparedStatement pstmt = null;
try {
// 清空表中数据
String delsql = "delete from " + DocumentCode.SCHEAM+ ".sys_user_xiucode where user_id='" + userId + "'";
pstmt = conn.prepareStatement(delsql);
pstmt.execute();
// 预编译SQL语句
pstmt = conn.prepareStatement("INSERT INTO " + DocumentCode.SCHEAM+ ".sys_user_xiucode" + " VALUES(?, ?)");
int cellcount = 0;
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(myfile));
StringBuffer StrB = new StringBuffer();
for (int i = 0; i < workbook.getNumberOfSheets(); i++) {
HSSFSheet sheet = workbook.getSheetAt(i);
if (null == sheet)
continue;
for (int j = 1; j <= sheet.getLastRowNum(); j++) {
HSSFRow row = sheet.getRow(j);
if (null == row)
continue;
for (int k = 0; k < row.getLastCellNum(); k++) {
HSSFCell cell = row.getCell(k);
String cellValue = "";
if (cell != null) {
if (cell.getCellType() == HSSFCell.CELL_TYPE_NUMERIC) {
String valuesub = "";
// cellValue = cell.getNumericCellValue() + "";
DecimalFormat df = new DecimalFormat("#");// 转换成整型
cellValue = df.format(cell.getNumericCellValue()); String valuerp = cellValue.replaceAll("\\.", "");
valuesub = (String) valuerp.subSequence(0, 8);
cellValue = valuesub;
} else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING) {
cellValue = cell.getStringCellValue();
}
StrB.append(cellValue).append(",");
}
// 为SQL插入值
if (!StringUtil.isEmpty(cellValue)) {
// values += "'" + cellValue + "',";
pstmt.setString(1, userId + "");
pstmt.setString(2, cellValue);
pstmt.addBatch();
cellcount++;
}
}
}
}
// 批量新增
if (cellcount > 0)
pstmt.executeBatch();
key = MD5Util.EncoderByMD5_32(StrB.toString());
values = " and '" + key + "'='" + key+ "' and XIU_CODE in (select xiu_code from "+ DocumentCode.SCHEAM + ".sys_user_xiucode where user_id='"+ userId + "')"; System.out.println("readExcel2003:" + values);
log.info(userId + "导入excel:" + cellcount);
} catch (Exception e) {
e.printStackTrace();
log.error(userId + "导入excel:", e);
} finally {
DBConnection.close(null, conn, pstmt);
}
String flag = "5";
session.setAttribute("excel", values);
session.setAttribute("uploadKey", key);
return null;
}
out = new FileOutputStream(getSavePath().replace('\\', '/') + "/" + upfileFileName);
out = new FileOutputStream("D://"+ upfileFileName);
这样的话,就完全没有问题,但是我上面那个输出流也没什么问题啊。。不解..
这里要指定绝对路径的,,不然怎么知道上传到哪里去呢?
你可以这样子呀:
out = new FileOutputStream(request.getRealpath(getSavePath()) + "/" + upfileFileName);就好了。