会先显示上传成功的界面,然后就报这个异常,文件上传 失败。
空指针报的是文件输出流。,谁帮我解决了,再加50分,,弄了好久了。
这个是浏览器上报的错。。,我发现了,action里面的execute方法竟然会执行两遍,,我写了个输出语句System.out.println(fileName);第一次是test.txt,第二次是null,,.找不到原因会执行两遍。

解决方案 »

  1.   

    action配置的地方,和action调用的地方发来看看啊
      

  2.   

    action如下:
    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";
        }
    }
      

  3.   

    struts.xml<?xml version="1.0" encoding="UTF-8" ?>
    <!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>
      

  4.   

    上传页面
    <%@ 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>
      

  5.   

    如果是提交2次的问题,检查下你jsp页面是否有<img src="#">,或者是其它包含#的地方,把这些代码去掉试下就行了,有些浏览器会有这种情况。
      

  6.   

    下面是我写的一个案例,LZ看下能否帮到你
    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;
    }
      

  7.   

    这个是将from表单提交变成ajax提交 从而判断是否成功,有返回值
      

  8.   

    你看看  http://bbs.csdn.net/topics/370053062?page=1#post-393499108
      

  9.   

    自动刷新的问题我改好了,我自己不知道什么时候,设置了一个refresh的content-type.现在的一个问题是,保存上传文件的文件夹依然为空,,我把输出流改了一下:
    out = new FileOutputStream(getSavePath().replace('\\', '/') + "/" + upfileFileName);
      

  10.   

    如果我把输出流改成:
    out = new FileOutputStream("D://"+ upfileFileName);
    这样的话,就完全没有问题,但是我上面那个输出流也没什么问题啊。。不解..
      

  11.   

    错了e,out = new FileOutputStream("D:/"+ upfileFileName);
      

  12.   


    这里要指定绝对路径的,,不然怎么知道上传到哪里去呢?
    你可以这样子呀:
    out = new FileOutputStream(request.getRealpath(getSavePath()) + "/" + upfileFileName);就好了。