The method subString(int, int) is undefined for the type String

3 respostas
A

olá pessoal,

Estou com um dúvida aqui estou fazendo um upload de arquivo com insert no banco, mas devido ao encrypted do form verifiquei que é necessário uma biblioteca a mais o “cos”. mas está dando o seguinte error:

org.apache.jasper.JasperException: Unable to compile class for JSP: 
JSP FileName:null
Java FileName:/C:/Tomcat55/work/Catalina/localhost/jsp//org/apache/jsp\bconhecimento_005fdocs_005fcadastro_005fupload_005ffile2_jsp.java


An error occurred at line: 8 in the generated java file
Only a type can be imported. com.oreilly.servlet.MultipartRequest resolves to a package
JSP FileName:/bconhecimento_docs_cadastro_upload_file2.jsp
Java FileName:/C:/Tomcat55/work/Catalina/localhost/jsp//org/apache/jsp\bconhecimento_005fdocs_005fcadastro_005fupload_005ffile2_jsp.java

An error occurred at line: 37 in the jsp file: /bconhecimento_docs_cadastro_upload_file2.jsp
MultipartRequest cannot be resolved to a type
34: 		int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
35: 
36: 		// creating a new file with the same name and writing the content in new file
37: 		MultipartRequest mpr = new MultipartRequest( request, pasta, 10240000); 		
38: 
39: 		String diretorio = "C:/Tomcat55/webapps/jsp/docs/";
40: 		String arquivo = mpr.getParameter("arquivo");

JSP FileName:/bconhecimento_docs_cadastro_upload_file2.jsp
Java FileName:/C:/Tomcat55/work/Catalina/localhost/jsp//org/apache/jsp\bconhecimento_005fdocs_005fcadastro_005fupload_005ffile2_jsp.java

An error occurred at line: 37 in the jsp file: /bconhecimento_docs_cadastro_upload_file2.jsp
MultipartRequest cannot be resolved to a type
34: 		int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
35: 
36: 		// creating a new file with the same name and writing the content in new file
37: 		MultipartRequest mpr = new MultipartRequest( request, pasta, 10240000); 		
38: 
39: 		String diretorio = "C:/Tomcat55/webapps/jsp/docs/";
40: 		String arquivo = mpr.getParameter("arquivo");

JSP FileName:/bconhecimento_docs_cadastro_upload_file2.jsp
Java FileName:/C:/Tomcat55/work/Catalina/localhost/jsp//org/apache/jsp\bconhecimento_005fdocs_005fcadastro_005fupload_005ffile2_jsp.java

An error occurred at line: 37 in the jsp file: /bconhecimento_docs_cadastro_upload_file2.jsp
pasta cannot be resolved
34: 		int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
35: 
36: 		// creating a new file with the same name and writing the content in new file
37: 		MultipartRequest mpr = new MultipartRequest( request, pasta, 10240000); 		
38: 
39: 		String diretorio = "C:/Tomcat55/webapps/jsp/docs/";
40: 		String arquivo = mpr.getParameter("arquivo");

Meu arquivo de formulário:

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.io.*" errorPage="" %>
<%
// *** Restrict Access To Page: Grant or deny access to this page
/*String MM_authorizedUsers="";
String MM_authFailedURL="publico_erro_login.jsp";
boolean MM_grantAccess=false;
if (session.getValue("MM_Username") != null && !session.getValue("MM_Username").equals("")) {
  if (true || (session.getValue("MM_UserAuthorization")=="") || 
          (MM_authorizedUsers.indexOf((String)session.getValue("MM_UserAuthorization")) >=0)) {
    MM_grantAccess = true;
  }
}
if (!MM_grantAccess) {
  String MM_qsChar = "?";
  if (MM_authFailedURL.indexOf("?") >= 0) MM_qsChar = "&";
  String MM_referrer = request.getRequestURI();
  if (request.getQueryString() != null) MM_referrer = MM_referrer + "?" + request.getQueryString();
  MM_authFailedURL = MM_authFailedURL + MM_qsChar + "accessdenied=" + java.net.URLEncoder.encode(MM_referrer);
  response.sendRedirect(response.encodeRedirectURL(MM_authFailedURL));
  return;
}*/
%>
<%@ include file="Connections/jsp.jsp" %>
<%
// *** Edit Operations: declare variables

// set the form action variable
String MM_editAction = request.getRequestURI();
if (request.getQueryString() != null && request.getQueryString().length() > 0) {

  String queryString = request.getQueryString();
  String tempStr = "";
  for (int i=0; i < queryString.length(); i++) {
    if (queryString.charAt(i) == '<') tempStr = tempStr + "&lt;";
    else if (queryString.charAt(i) == '>') tempStr = tempStr + "&gt;";
    else if (queryString.charAt(i) == '"') tempStr = tempStr +  """;
    else tempStr = tempStr + queryString.charAt(i);
  }
  MM_editAction += "?" + tempStr;
}

// connection information
String MM_editDriver = null, MM_editConnection = null, MM_editUserName = null, MM_editPassword = null;

// redirect information
String MM_editRedirectUrl = null;

// query string to execute
StringBuffer MM_editQuery = null;

// boolean to abort record edit
boolean MM_abortEdit = false;

// table information
String MM_editTable = null, MM_editColumn = null, MM_recordId = null;

// form field information
String[] MM_fields = null, MM_columns = null;
%>
<%
// *** Insert Record: set variables

if (request.getParameter("MM_insert") != null && request.getParameter("MM_insert").toString().equals("form1")) {

  out.println("parte3");

  MM_editDriver     = MM_jsp_DRIVER;
  MM_editConnection = MM_jsp_STRING;
  MM_editUserName   = MM_jsp_USERNAME;
  MM_editPassword   = MM_jsp_PASSWORD;
  MM_editTable  = "jsp.documentos";
  MM_editRedirectUrl = "publico_sucesso.html";
  String MM_fieldsStr = "descricao|value|caminho|value";
  String MM_columnsStr = "descricao|',none,''|caminho|',none,''";

  // create the MM_fields and MM_columns arrays
  java.util.StringTokenizer tokens = new java.util.StringTokenizer(MM_fieldsStr,"|");
  MM_fields = new String[tokens.countTokens()];
  for (int i=0; tokens.hasMoreTokens(); i++) MM_fields[i] = tokens.nextToken();

  tokens = new java.util.StringTokenizer(MM_columnsStr,"|");
  MM_columns = new String[tokens.countTokens()];
  for (int i=0; tokens.hasMoreTokens(); i++) MM_columns[i] = tokens.nextToken();

  // set the form values
  for (int i=0; i+1 < MM_fields.length; i+=2) {
    MM_fields[i+1] = ((request.getParameter(MM_fields[i])!=null)?(String)request.getParameter(MM_fields[i]):"");
  }
 
  // append the query string to the redirect URL
  if (MM_editRedirectUrl.length() != 0 && request.getQueryString() != null) {
    MM_editRedirectUrl += ((MM_editRedirectUrl.indexOf('?') == -1)?"?":"&") + request.getQueryString();
  }
}
%>
<%
// *** Insert Record: construct a sql insert statement and execute it

if (request.getParameter("MM_insert") != null) {

  // create the insert sql statement
  StringBuffer MM_tableValues = new StringBuffer(), MM_dbValues = new StringBuffer();
  for (int i=0; i+1 < MM_fields.length; i+=2) {
    String formVal = MM_fields[i+1];
    String elem;
    java.util.StringTokenizer tokens = new java.util.StringTokenizer(MM_columns[i+1],",");
    String delim    = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    String altVal   = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    String emptyVal = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    if (formVal.length() == 0) {
      formVal = emptyVal;
    } else {
      if (altVal.length() != 0) {
        formVal = altVal;
      } else if (delim.compareTo("'") == 0) {  // escape quotes
        StringBuffer escQuotes = new StringBuffer(formVal);
        for (int j=0; j < escQuotes.length(); j++)
          if (escQuotes.charAt(j) == '\'') escQuotes.insert(j++,'\'');
        formVal = "'" + escQuotes + "'";
      } else {
        formVal = delim + formVal + delim;
      }
    }
    MM_tableValues.append((i!=0)?",":"").append(MM_columns[i]);
    MM_dbValues.append((i!=0)?",":"").append(formVal);
  }
  MM_editQuery = new StringBuffer("insert into " + MM_editTable);
  MM_editQuery.append(" (").append(MM_tableValues.toString()).append(") values (");
  MM_editQuery.append(MM_dbValues.toString()).append(")");
  
  if (!MM_abortEdit) {
    // finish the sql and execute it
    Driver MM_driver = (Driver)Class.forName(MM_editDriver).newInstance();
    Connection MM_connection = DriverManager.getConnection(MM_editConnection,MM_editUserName,MM_editPassword);
    PreparedStatement MM_editStatement = MM_connection.prepareStatement(MM_editQuery.toString());
    MM_editStatement.executeUpdate();
    MM_connection.close();

    // redirect with URL parameters
    if (MM_editRedirectUrl.length() != 0) {
      response.sendRedirect(response.encodeRedirectURL(MM_editRedirectUrl));
      return;
    }
  }
}
%>
<%
Driver Driverultimo_arquivo = (Driver)Class.forName(MM_jsp_DRIVER).newInstance();
Connection Connultimo_arquivo = DriverManager.getConnection(MM_jsp_STRING,MM_jsp_USERNAME,MM_jsp_PASSWORD);
PreparedStatement Statementultimo_arquivo = Connultimo_arquivo.prepareStatement("SELECT count(*) as total  FROM jsp.documentos");
ResultSet ultimo_arquivo = Statementultimo_arquivo.executeQuery();
boolean ultimo_arquivo_isEmpty = !ultimo_arquivo.next();
boolean ultimo_arquivo_hasData = !ultimo_arquivo_isEmpty;
Object ultimo_arquivo_data;
int ultimo_arquivo_numRows = 0;
%>
<%
int Repeat1__numRows = -1;
int Repeat1__index = 0;
ultimo_arquivo_numRows += Repeat1__numRows;
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Cadastro de Documentos</title>
<script>
function getStats(fName){

	var fileinput = fName; 
	if(!fileinput ) return ""; 
	if( fileinput.length == 0 ) return ""; 
	var dot = fileinput.lastIndexOf("."); 
	if( dot == -1 ) return ""; 

	//Pega a extensão do arquivo com ponto
	var extension = fileinput.substr(dot,fileinput.length); 
	document.forms.form1.extensao.value = extension;

	//Pega o arquivo com a extensão
	fullName = fName;
	shortName = fullName.match(/[^\/\\]+$/);
	document.forms.form1.nomearquivo.value = shortName;

	//Pega somente o arquivo sem a extensão
	var extensao = document.forms.form1.extensao.value; 
	var tamanhoExtensao = extensao.length; 
	var arquivo = document.forms.form1.nomearquivo.value; 
	var tamanhoArquivo = arquivo.length;
	var sonome = arquivo.substr(0, tamanhoArquivo - tamanhoExtensao);
	document.forms.form1.sonome.value = sonome;
	
	//Pega o total de arquivo do banco e soma mais 1 (+)
	var totArqBD = document.forms.form1.totarq.value;
	var sum = parseInt(totArqBD) + parseInt(1);
	var nomeBD = sum;
	document.forms.form1.nomebanco.value = nomeBD + extension;	
	
	//Passa para o campo que ira inserir no banco o nome novo
	document.forms.form1.caminho.value = document.forms.form1.nomebanco.value;
	document.forms.form2.arquivo.value = document.forms.form1.nomebanco.value;
	
}
</script>
<script language="JavaScript" >
function enviardados(){

	if (document.form1.descricao.value=="")
	{
		alert( "Preencha o campo [Descrição]!" );
		document.form1.descricao.focus();
		return false;
	}
	if (document.form1.caminho.value=="")
	{
		alert( "Preencha o campo [CaminhoOculto]!" );
		document.form1.caminho.focus();
		return false;
	}
	if (document.form2.file.value=="")
	{
		alert( "Preencha o campo [Documento]!" );
		document.form2.file.focus();
		return false;
	}

	return true;
}
</script>
<link href="estilo/estilo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<jsp:include page="i_topo.jsp" flush="true" />
<br />
<jsp:include page="i_topo_admin.jsp" flush="true" />
<div style="margin-left:50px">
<p class="simples"><strong>:: Cadastro de Documentos</strong></p>
<form method="post" action="<%=MM_editAction%>" name="form1">
  <table width="900">
    <tr>
      <td width="180" align="right" class="simples">Descri&ccedil;&atilde;o do Documento:</td>
      <td><input name="descricao" type="text" class="simples" value="" size="50"></td>
    </tr>
    <tr>
      <td align="right" class="simples">Nome do Arquivo </td>
      <td><input name="nomearquivo" type="text" class="simples" id="nomearquivo" value="" /></td>
    </tr>
    <tr>
      <td align="right" class="simples">Extens&atilde;o do Arquivo </td>
      <td><input name="extensao" type="text" class="simples" id="extensao" value="" /></td>
    </tr>
    <tr>
      <td align="right" class="simples">Somente Nome (Sem extens&atilde;o) </td>
      <td><input name="sonome" type="text" class="simples" id="sonome" value="" /></td>
    </tr>
    <tr>
      <td align="right" class="simples">Total de arquivo no banco </td>
	  <td>
      <input name="totarq" type="text" class="simples" id="totarq" value="<%=(((ultimo_arquivo_data = ultimo_arquivo.getObject("total"))==null || ultimo_arquivo.wasNull())?"":ultimo_arquivo_data)%>" />	  </td>
    </tr>
    <tr>
      <td align="right" class="simples">Nome que ir&aacute; para o banco </td>
      <td><input name="nomebanco" type="text" class="simples" id="nomebanco" value="" /></td>
    </tr>
  </table>
   <input type="hidden" name="caminho" value="">
  <input type="hidden" name="MM_insert" value="form1">
</form>
<form method="post" action="bconhecimento_docs_cadastro_upload_file2.jsp" name="form2" enctype="multipart/form-data" onSubmit="document.form1.submit()">
  <table width="700">
    <tr>
      <td width="150" align="right" class="simples">Documento:</td>
      <td><input name="file" type="file" class="simples" onChange="javascript:getStats(this.value)" value="" size="70"></td>
    </tr>
    <tr>
      <td align="right" class="simples">Nome Final:</td>
      <td><input name="arquivo" type="text" class="vermelho" value=""></td>
    </tr>
    <tr>
      <td align="center">&nbsp;</td>
      <td><input name="submit" type="submit" class="simples" value="Inserir" onclick="return enviardados();" /> 
      <input name="Reset" type="reset" class="simples" value="Limpar" /></td>
    </tr>
  </table>  
</form>
<p>&nbsp;</p>
<p><a href="admin_menu.jsp" class="simples">.:.. voltar</a></p>
</div>
<jsp:include page="i_base.jsp" flush="true" />
</body>
</html>
<%
ultimo_arquivo.close();
Statementultimo_arquivo.close();
Connultimo_arquivo.close();
%>

Arquivo que faz o upload:

<%@ page import="java.util.*,java.io.*,com.oreilly.servlet.MultipartRequest" %>  
<%
	//to get the content type information from JSP Request Header
	String contentType = request.getContentType();
	//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
	if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
 		DataInputStream in = new DataInputStream(request.getInputStream());
		//we are taking the length of Content type data
		int formDataLength = request.getContentLength();
		byte dataBytes[] = new byte[formDataLength];
		int byteRead = 0;
		int totalBytesRead = 0;
		//this loop converting the uploaded file into byte code
		while (totalBytesRead < formDataLength) {
			byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
			totalBytesRead += byteRead;
			}

		String file = new String(dataBytes);
		//for saving the file name
		String saveFile = file.substring(file.indexOf("filename=\"") + 10);		
		saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
		saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
		int lastIndex = contentType.lastIndexOf("=");
		String boundary = contentType.substring(lastIndex + 1,contentType.length());
		int pos;
		//extracting the index of file 
		pos = file.indexOf("filename=\"");
		pos = file.indexOf("\n", pos) + 1;
		pos = file.indexOf("\n", pos) + 1;
		pos = file.indexOf("\n", pos) + 1;
		int boundaryLocation = file.indexOf(boundary, pos) - 4;
		int startPos = ((file.substring(0, pos)).getBytes()).length;
		int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;

		// creating a new file with the same name and writing the content in new file
		MultipartRequest mpr = new MultipartRequest( request, pasta, 10240000); 		

		String diretorio = "C:/Tomcat55/webapps/jsp/docs/";
		String arquivo = mpr.getParameter("arquivo");
		saveFile = diretorio + arquivo;		
	
		FileOutputStream fileOut = new FileOutputStream(saveFile);
		fileOut.write(dataBytes, startPos, (endPos - startPos));
		fileOut.flush();
		fileOut.close();
		
		//response.sendRedirect("publico_sucesso.html");
	}
	
%>

Obrigado pela atenção

3 Respostas

A

Estou com este erro agora não estou utilizando mais o cos, estou usando somente java:

An error occurred at line: 209 in the jsp file: /bconhecimento_docs_cadastro2.jsp

The method subString(int, int) is undefined for the type String

206: 	//pega o tamanho da extensão do arquivo

207: 	int tamanhoExtensao = (tamanho - dot);

208: 	//pega somente a extensão do arquivo com ponto

209:     String extension = fileinput.subString(dot,tamanhoExtensao);

210: 	

211: %>

212:
<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.io.*" errorPage="" %>
<%
// *** Restrict Access To Page: Grant or deny access to this page
/*String MM_authorizedUsers="";
String MM_authFailedURL="publico_erro_login.jsp";
boolean MM_grantAccess=false;
if (session.getValue("MM_Username") != null && !session.getValue("MM_Username").equals("")) {
  if (true || (session.getValue("MM_UserAuthorization")=="") || 
          (MM_authorizedUsers.indexOf((String)session.getValue("MM_UserAuthorization")) >=0)) {
    MM_grantAccess = true;
  }
}
if (!MM_grantAccess) {
  String MM_qsChar = "?";
  if (MM_authFailedURL.indexOf("?") >= 0) MM_qsChar = "&";
  String MM_referrer = request.getRequestURI();
  if (request.getQueryString() != null) MM_referrer = MM_referrer + "?" + request.getQueryString();
  MM_authFailedURL = MM_authFailedURL + MM_qsChar + "accessdenied=" + java.net.URLEncoder.encode(MM_referrer);
  response.sendRedirect(response.encodeRedirectURL(MM_authFailedURL));
  return;
}*/
%>
<%@ include file="Connections/jsp.jsp" %>
<%
// *** Edit Operations: declare variables

// set the form action variable
String MM_editAction = request.getRequestURI();
if (request.getQueryString() != null && request.getQueryString().length() > 0) {

  String queryString = request.getQueryString();
  String tempStr = "";
  for (int i=0; i < queryString.length(); i++) {
    if (queryString.charAt(i) == '<') tempStr = tempStr + "&lt;";
    else if (queryString.charAt(i) == '>') tempStr = tempStr + "&gt;";
    else if (queryString.charAt(i) == '"') tempStr = tempStr +  """;
    else tempStr = tempStr + queryString.charAt(i);
  }
  MM_editAction += "?" + tempStr;
}

// connection information
String MM_editDriver = null, MM_editConnection = null, MM_editUserName = null, MM_editPassword = null;

// redirect information
String MM_editRedirectUrl = null;

// query string to execute
StringBuffer MM_editQuery = null;

// boolean to abort record edit
boolean MM_abortEdit = false;

// table information
String MM_editTable = null, MM_editColumn = null, MM_recordId = null;

// form field information
String[] MM_fields = null, MM_columns = null;
%>
<%
// *** Insert Record: set variables

if (request.getParameter("MM_insert") != null && request.getParameter("MM_insert").toString().equals("form1")) {

  MM_editDriver     = MM_jsp_DRIVER;
  MM_editConnection = MM_jsp_STRING;
  MM_editUserName   = MM_jsp_USERNAME;
  MM_editPassword   = MM_jsp_PASSWORD;
  MM_editTable  = "jsp.documentos";
  MM_editRedirectUrl = "publico_sucesso.html";
  String MM_fieldsStr = "descricao|value|caminho|value";
  String MM_columnsStr = "descricao|',none,''|caminho|',none,''";

  // create the MM_fields and MM_columns arrays
  java.util.StringTokenizer tokens = new java.util.StringTokenizer(MM_fieldsStr,"|");
  MM_fields = new String[tokens.countTokens()];
  for (int i=0; tokens.hasMoreTokens(); i++) MM_fields[i] = tokens.nextToken();

  tokens = new java.util.StringTokenizer(MM_columnsStr,"|");
  MM_columns = new String[tokens.countTokens()];
  for (int i=0; tokens.hasMoreTokens(); i++) MM_columns[i] = tokens.nextToken();

  // set the form values
  for (int i=0; i+1 < MM_fields.length; i+=2) {
    MM_fields[i+1] = ((request.getParameter(MM_fields[i])!=null)?(String)request.getParameter(MM_fields[i]):"");
  }
 
  // append the query string to the redirect URL
  if (MM_editRedirectUrl.length() != 0 && request.getQueryString() != null) {
    MM_editRedirectUrl += ((MM_editRedirectUrl.indexOf('?') == -1)?"?":"&") + request.getQueryString();
  }
}
%>
<%
// *** Insert Record: construct a sql insert statement and execute it

if (request.getParameter("MM_insert") != null) {

  // create the insert sql statement
  StringBuffer MM_tableValues = new StringBuffer(), MM_dbValues = new StringBuffer();
  for (int i=0; i+1 < MM_fields.length; i+=2) {
    String formVal = MM_fields[i+1];
    String elem;
    java.util.StringTokenizer tokens = new java.util.StringTokenizer(MM_columns[i+1],",");
    String delim    = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    String altVal   = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    String emptyVal = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    if (formVal.length() == 0) {
      formVal = emptyVal;
    } else {
      if (altVal.length() != 0) {
        formVal = altVal;
      } else if (delim.compareTo("'") == 0) {  // escape quotes
        StringBuffer escQuotes = new StringBuffer(formVal);
        for (int j=0; j < escQuotes.length(); j++)
          if (escQuotes.charAt(j) == '\'') escQuotes.insert(j++,'\'');
        formVal = "'" + escQuotes + "'";
      } else {
        formVal = delim + formVal + delim;
      }
    }
    MM_tableValues.append((i!=0)?",":"").append(MM_columns[i]);
    MM_dbValues.append((i!=0)?",":"").append(formVal);
  }
  MM_editQuery = new StringBuffer("insert into " + MM_editTable);
  MM_editQuery.append(" (").append(MM_tableValues.toString()).append(") values (");
  MM_editQuery.append(MM_dbValues.toString()).append(")");
  
  if (!MM_abortEdit) {
    // finish the sql and execute it
    Driver MM_driver = (Driver)Class.forName(MM_editDriver).newInstance();
    Connection MM_connection = DriverManager.getConnection(MM_editConnection,MM_editUserName,MM_editPassword);
    PreparedStatement MM_editStatement = MM_connection.prepareStatement(MM_editQuery.toString());
    MM_editStatement.executeUpdate();
    MM_connection.close();

    // redirect with URL parameters
    if (MM_editRedirectUrl.length() != 0) {
      response.sendRedirect(response.encodeRedirectURL(MM_editRedirectUrl));
      return;
    }
  }
}


//SQL teste
Driver Driverultimo_arquivo = (Driver)Class.forName(MM_jsp_DRIVER).newInstance();
Connection Connultimo_arquivo = DriverManager.getConnection(MM_jsp_STRING,MM_jsp_USERNAME,MM_jsp_PASSWORD);
PreparedStatement Statementultimo_arquivo = Connultimo_arquivo.prepareStatement("SELECT count(*) as total  FROM jsp.documentos");
ResultSet ultimo_arquivo = Statementultimo_arquivo.executeQuery();
boolean ultimo_arquivo_isEmpty = !ultimo_arquivo.next();
boolean ultimo_arquivo_hasData = !ultimo_arquivo_isEmpty;
Object ultimo_arquivo_data;
int ultimo_arquivo_numRows = 0;

//Contador	
int Repeat1__numRows = -1;
int Repeat1__index = 0;
ultimo_arquivo_numRows += Repeat1__numRows;

//Pega ultimo
ultimo_arquivo_data = ultimo_arquivo.getObject("total");

//importa arquivo para o servidor

//to get the content type information from JSP Request Header

String contentType = request.getContentType();
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
	DataInputStream in = new DataInputStream(request.getInputStream());
	//we are taking the length of Content type data
	int formDataLength = request.getContentLength();
	byte dataBytes[] = new byte[formDataLength];
	int byteRead = 0;
	int totalBytesRead = 0;
	//this loop converting the uploaded file into byte code
	while (totalBytesRead < formDataLength) {
		byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
		totalBytesRead += byteRead;
		}

	String file = new String(dataBytes);
	//for saving the file name
	String saveFile = file.substring(file.indexOf("filename=\"") + 10);
	saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
	saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
	int lastIndex = contentType.lastIndexOf("=");
	String boundary = contentType.substring(lastIndex + 1,contentType.length());
	int pos;
	//extracting the index of file 
	pos = file.indexOf("filename=\"");
	pos = file.indexOf("\n", pos) + 1;
	pos = file.indexOf("\n", pos) + 1;
	pos = file.indexOf("\n", pos) + 1;
	int boundaryLocation = file.indexOf(boundary, pos) - 4;
	int startPos = ((file.substring(0, pos)).getBytes()).length;
	int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
	
	//Pega nome do arquivo
	String fileinput = saveFile;   
	//pega o local do ponto
    int dot = fileinput.lastIndexOf("."); 
	//pega o tamanho nome do arquivo
	int tamanho = fileinput.length();
	//pega o tamanho da extensão do arquivo
	int tamanhoExtensao = (tamanho - dot);
	//pega somente a extensão do arquivo com ponto
    String extension = fileinput.subString(dot,tamanhoExtensao);   
	
%>
<script language="JavaScript" >
window.alert('Fileput:');
window.alert(<%=fileinput%>);
window.alert('Dot:');
window.alert(<%=dot%>);
window.alert('Tamanho Extensao:');
window.alert(<%=tamanhoExtensao%>);
</script>
<%

	// creating a new file with the same name and writing the content in new file
	String diretorio = "C:/Tomcat55/webapps/jsp/docs/";
	String arquivo = ultimo_arquivo_data.toString();
	saveFile = diretorio + arquivo;

	FileOutputStream fileOut = new FileOutputStream(saveFile);
	fileOut.write(dataBytes, startPos, (endPos - startPos));
	fileOut.flush();
	fileOut.close();
	
	//response.sendRedirect("publico_sucesso.html");
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Cadastro de Documentos</title>
<script language="JavaScript" >
function nomeArquivo(fName){  
  
	document.forms.form1.caminho.value = fName;
	document.forms.form2.arquivo.value = fName;

}	
function enviardados(){

	if (document.form1.descricao.value=="")
	{
		alert( "Preencha o campo [Descrição]!" );
		document.form1.descricao.focus();
		return false;
	}
	if (document.form1.caminho.value=="")
	{
		alert( "Preencha o campo [CaminhoOculto]!" );
		document.form1.caminho.focus();
		return false;
	}
	if (document.form2.file.value=="")
	{
		alert( "Preencha o campo [Documento]!" );
		document.form2.file.focus();
		return false;
	}

	return true;
}
</script>
<link href="estilo/estilo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<jsp:include page="i_topo.jsp" flush="true" />
<br />
<jsp:include page="i_topo_admin.jsp" flush="true" />
<div style="margin-left:50px">
<p class="simples"><strong>:: Cadastro de Documentos</strong></p>
<form method="post" action="<%=MM_editAction%>" name="form1">
  <table width="900">
    <tr>
      <td width="180" align="right" valign="top" class="simples">Descri&ccedil;&atilde;o do Documento:</td>
      <td><textarea name="descricao" cols="72" rows="5" class="simples"></textarea></td>
    </tr>
  </table>
   <input type="hidden" name="caminho" value="">
  <input type="hidden" name="MM_insert" value="form1">
</form>
<hr size="1" width="500" align="left" />
<form method="post" action="<%=MM_editAction%>" name="form2" enctype="multipart/form-data" onSubmit="document.form1.submit()">
  <table width="900">
    <tr>
      <td width="180" align="right" class="simples">Documento:</td>
      <td><input name="file" type="file" class="simples" onChange="javascript:nomeArquivo(this.value)" value="" size="70"></td>
    </tr>
    <tr>
      <td align="right" class="simples">Nome Final:</td>
      <td><input name="arquivo" type="text" class="vermelho" value="" size="70" readonly="yes"></td>
    </tr>
    <tr>
      <td align="center">&nbsp;</td>
      <td><input name="submit" type="submit" class="simples" value="Inserir" onClick="return enviardados();" /> 
      <input name="Reset" type="reset" class="simples" value="Limpar" /></td>
    </tr>
  </table>  
</form>
<p>&nbsp;</p>
<p><a href="admin_menu.jsp" class="simples">.:.. voltar</a></p>
</div>
<jsp:include page="i_base.jsp" flush="true" />
</body>
</html>
<%
ultimo_arquivo.close();
Statementultimo_arquivo.close();
Connultimo_arquivo.close();
%>
T

Aconselho sempre a olhar o Javadoc antes de mais nada. O nome do método é substring, não subString.

http://java.sun.com/javase/6/docs/api/java/lang/String.html

A

Resolvi meu problema, verifiquei o código novamente.
Com o código abaixo eu faço o upload do arquivo e o renomeio pelo seu indetificador na base de dados

<%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,java.io.*" errorPage="" %>
<%
// *** Restrict Access To Page: Grant or deny access to this page
/*String MM_authorizedUsers="";
String MM_authFailedURL="publico_erro_login.jsp";
boolean MM_grantAccess=false;
if (session.getValue("MM_Username") != null && !session.getValue("MM_Username").equals("")) {
  if (true || (session.getValue("MM_UserAuthorization")=="") || 
          (MM_authorizedUsers.indexOf((String)session.getValue("MM_UserAuthorization")) >=0)) {
    MM_grantAccess = true;
  }
}
if (!MM_grantAccess) {
  String MM_qsChar = "?";
  if (MM_authFailedURL.indexOf("?") >= 0) MM_qsChar = "&";
  String MM_referrer = request.getRequestURI();
  if (request.getQueryString() != null) MM_referrer = MM_referrer + "?" + request.getQueryString();
  MM_authFailedURL = MM_authFailedURL + MM_qsChar + "accessdenied=" + java.net.URLEncoder.encode(MM_referrer);
  response.sendRedirect(response.encodeRedirectURL(MM_authFailedURL));
  return;
}*/
%>
<%@ include file="Connections/jsp.jsp" %>
<%
// *** Edit Operations: declare variables

// set the form action variable
String MM_editAction = request.getRequestURI();
if (request.getQueryString() != null && request.getQueryString().length() > 0) {

  String queryString = request.getQueryString();
  String tempStr = "";
  for (int i=0; i < queryString.length(); i++) {
    if (queryString.charAt(i) == '<') tempStr = tempStr + "&lt;";
    else if (queryString.charAt(i) == '>') tempStr = tempStr + "&gt;";
    else if (queryString.charAt(i) == '"') tempStr = tempStr +  """;
    else tempStr = tempStr + queryString.charAt(i);
  }
  MM_editAction += "?" + tempStr;
}

// connection information
String MM_editDriver = null, MM_editConnection = null, MM_editUserName = null, MM_editPassword = null;

// redirect information
String MM_editRedirectUrl = null;

// query string to execute
StringBuffer MM_editQuery = null;

// boolean to abort record edit
boolean MM_abortEdit = false;

// table information
String MM_editTable = null, MM_editColumn = null, MM_recordId = null;

// form field information
String[] MM_fields = null, MM_columns = null;
%>
<%
// *** Insert Record: set variables

if (request.getParameter("MM_insert") != null && request.getParameter("MM_insert").toString().equals("form1")) {

  MM_editDriver     = MM_jsp_DRIVER;
  MM_editConnection = MM_jsp_STRING;
  MM_editUserName   = MM_jsp_USERNAME;
  MM_editPassword   = MM_jsp_PASSWORD;
  MM_editTable  = "jsp.documentos";
  MM_editRedirectUrl = "publico_sucesso.html";
  String MM_fieldsStr = "descricao|value|caminho|value";
  String MM_columnsStr = "descricao|',none,''|caminho|',none,''";

  // create the MM_fields and MM_columns arrays
  java.util.StringTokenizer tokens = new java.util.StringTokenizer(MM_fieldsStr,"|");
  MM_fields = new String[tokens.countTokens()];
  for (int i=0; tokens.hasMoreTokens(); i++) MM_fields[i] = tokens.nextToken();

  tokens = new java.util.StringTokenizer(MM_columnsStr,"|");
  MM_columns = new String[tokens.countTokens()];
  for (int i=0; tokens.hasMoreTokens(); i++) MM_columns[i] = tokens.nextToken();

  // set the form values
  for (int i=0; i+1 < MM_fields.length; i+=2) {
    MM_fields[i+1] = ((request.getParameter(MM_fields[i])!=null)?(String)request.getParameter(MM_fields[i]):"");
  }
 
  // append the query string to the redirect URL
  if (MM_editRedirectUrl.length() != 0 && request.getQueryString() != null) {
    MM_editRedirectUrl += ((MM_editRedirectUrl.indexOf('?') == -1)?"?":"&") + request.getQueryString();
  }
}
%>
<%
// *** Insert Record: construct a sql insert statement and execute it

if (request.getParameter("MM_insert") != null) {

  // create the insert sql statement
  StringBuffer MM_tableValues = new StringBuffer(), MM_dbValues = new StringBuffer();
  for (int i=0; i+1 < MM_fields.length; i+=2) {
    String formVal = MM_fields[i+1];
    String elem;
    java.util.StringTokenizer tokens = new java.util.StringTokenizer(MM_columns[i+1],",");
    String delim    = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    String altVal   = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    String emptyVal = ((elem = (String)tokens.nextToken()) != null && elem.compareTo("none")!=0)?elem:"";
    if (formVal.length() == 0) {
      formVal = emptyVal;
    } else {
      if (altVal.length() != 0) {
        formVal = altVal;
      } else if (delim.compareTo("'") == 0) {  // escape quotes
        StringBuffer escQuotes = new StringBuffer(formVal);
        for (int j=0; j < escQuotes.length(); j++)
          if (escQuotes.charAt(j) == '\'') escQuotes.insert(j++,'\'');
        formVal = "'" + escQuotes + "'";
      } else {
        formVal = delim + formVal + delim;
      }
    }
    MM_tableValues.append((i!=0)?",":"").append(MM_columns[i]);
    MM_dbValues.append((i!=0)?",":"").append(formVal);
  }
  MM_editQuery = new StringBuffer("insert into " + MM_editTable);
  MM_editQuery.append(" (").append(MM_tableValues.toString()).append(") values (");
  MM_editQuery.append(MM_dbValues.toString()).append(")");
  
  if (!MM_abortEdit) {
    // finish the sql and execute it
    Driver MM_driver = (Driver)Class.forName(MM_editDriver).newInstance();
    Connection MM_connection = DriverManager.getConnection(MM_editConnection,MM_editUserName,MM_editPassword);
    PreparedStatement MM_editStatement = MM_connection.prepareStatement(MM_editQuery.toString());
    MM_editStatement.executeUpdate();
    MM_connection.close();

    // redirect with URL parameters
    if (MM_editRedirectUrl.length() != 0) {
      response.sendRedirect(response.encodeRedirectURL(MM_editRedirectUrl));
      return;
    }
  }
}


//SQL teste
Driver Driverultimo_arquivo = (Driver)Class.forName(MM_jsp_DRIVER).newInstance();
Connection Connultimo_arquivo = DriverManager.getConnection(MM_jsp_STRING,MM_jsp_USERNAME,MM_jsp_PASSWORD);
PreparedStatement Statementultimo_arquivo = Connultimo_arquivo.prepareStatement("SELECT count(*) as total  FROM jsp.documentos");
ResultSet ultimo_arquivo = Statementultimo_arquivo.executeQuery();
boolean ultimo_arquivo_isEmpty = !ultimo_arquivo.next();
boolean ultimo_arquivo_hasData = !ultimo_arquivo_isEmpty;
Object ultimo_arquivo_data;
int ultimo_arquivo_numRows = 0;

//Contador	
int Repeat1__numRows = -1;
int Repeat1__index = 0;
ultimo_arquivo_numRows += Repeat1__numRows;

//Pega ultimo
ultimo_arquivo_data = ultimo_arquivo.getObject("total");

//importa arquivo para o servidor

//to get the content type information from JSP Request Header

String contentType = request.getContentType();
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
	DataInputStream in = new DataInputStream(request.getInputStream());
	//we are taking the length of Content type data
	int formDataLength = request.getContentLength();
	byte dataBytes[] = new byte[formDataLength];
	int byteRead = 0;
	int totalBytesRead = 0;
	//this loop converting the uploaded file into byte code
	while (totalBytesRead < formDataLength) {
		byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
		totalBytesRead += byteRead;
		}

	String file = new String(dataBytes);
	//for saving the file name
	String saveFile = file.substring(file.indexOf("filename=\"") + 10);
	saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
	saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
	int lastIndex = contentType.lastIndexOf("=");
	String boundary = contentType.substring(lastIndex + 1,contentType.length());
	int pos;
	//extracting the index of file 
	pos = file.indexOf("filename=\"");
	pos = file.indexOf("\n", pos) + 1;
	pos = file.indexOf("\n", pos) + 1;
	pos = file.indexOf("\n", pos) + 1;
	int boundaryLocation = file.indexOf(boundary, pos) - 4;
	int startPos = ((file.substring(0, pos)).getBytes()).length;
	int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
	
	//Pega nome do arquivo
	String fileinput = "nulo";   
	fileinput = saveFile;
	//pega o local do ponto
    int dot = fileinput.lastIndexOf("."); 
	//pega o tamanho nome do arquivo
	int tamanho = fileinput.length();
	//pega o tamanho da extensão do arquivo
	int tamanhoExtensao = (tamanho - dot);
	//pega somente a extensão do arquivo com ponto
    String extension = fileinput.substring(dot, tamanho);  
	
	// creating a new file with the same name and writing the content in new file
	String diretorio = "C:/Tomcat55/webapps/jsp/docs/";
	String arquivo = ultimo_arquivo_data.toString() + extension;
	saveFile = diretorio + arquivo;

	FileOutputStream fileOut = new FileOutputStream(saveFile);
	fileOut.write(dataBytes, startPos, (endPos - startPos));
	fileOut.flush();
	fileOut.close();
	
	//response.sendRedirect("publico_sucesso.html");
}
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Cadastro de Documentos</title>
<script language="JavaScript" >
function nomeArquivo(fName){

	var fileinput = fName; 
	if(!fileinput ) return ""; 
	if( fileinput.length == 0 ) return ""; 
	var dot = fileinput.lastIndexOf("."); 
	if( dot == -1 ) return ""; 

	//Pega a extensão do arquivo com ponto
	var extension = fileinput.substr(dot,fileinput.length); 
	document.forms.form1.extensao.value = extension;

	//Pega o arquivo com a extensão
	fullName = fName;
	shortName = fullName.match(/[^\/\\]+$/);
	document.forms.form1.nomearquivo.value = shortName;

	//Pega somente o arquivo sem a extensão
	var extensao = document.forms.form1.extensao.value; 
	var tamanhoExtensao = extensao.length; 
	var arquivo = document.forms.form1.nomearquivo.value; 
	var tamanhoArquivo = arquivo.length;
	var sonome = arquivo.substr(0, tamanhoArquivo - tamanhoExtensao);
	document.forms.form1.sonome.value = sonome;
	
	//Pega o total de arquivo do banco e soma mais 1 (+)
	var totArqBD = document.forms.form1.totarq.value;
	var sum = parseInt(totArqBD) + parseInt(1);
	var nomeBD = sum;
	document.forms.form1.nomebanco.value = nomeBD + extension;	
	
	//Passa para o campo que ira inserir no banco o nome novo
	document.forms.form1.caminho.value = document.forms.form1.nomebanco.value;

}	
function enviardados(){

	if (document.form1.descricao.value=="")
	{
		alert( "Preencha o campo [Descrição]!" );
		document.form1.descricao.focus();
		return false;
	}
	if (document.form1.caminho.value=="")
	{
		alert( "Preencha o campo [CaminhoOculto]!" );
		document.form1.caminho.focus();
		return false;
	}
	if (document.form2.file.value=="")
	{
		alert( "Preencha o campo [Documento]!" );
		document.form2.file.focus();
		return false;
	}
	return true;
}
</script>
<link href="estilo/estilo.css" rel="stylesheet" type="text/css" />
</head>
<body>
<jsp:include page="i_topo.jsp" flush="true" />
<br />
<jsp:include page="i_topo_admin.jsp" flush="true" />
<div style="margin-left:50px">
<p class="simples"><strong>:: Cadastro de Documentos</strong></p>
<form method="post" action="<%=MM_editAction%>" name="form1">
  <table width="900">
    <tr>
      <td width="180" align="right" valign="top" class="simples">Descri&ccedil;&atilde;o do Documento:</td>
      <td><textarea name="descricao" cols="72" rows="5" class="simples"></textarea></td>
    </tr>
  </table>
  <input name="extensao" type="hidden" class="vermelho" id="extensao" value="" size="70"/>
  <input name="nomearquivo" type="hidden" class="vermelho" id="nomearquivo" value="" size="70" />
  <input name="sonome" type="hidden" class="vermelho" id="sonome" value="" size="70"/>
  <input name="totarq" type="hidden" class="vermelho" id="totarq" value="<%=(((ultimo_arquivo_data = ultimo_arquivo.getObject("total"))==null || ultimo_arquivo.wasNull())?"":ultimo_arquivo_data)%>" size="70"/>
  <input name="caminho" type="hidden" class="vermelho" id="caminho" value="" size="70"/>
  <input name="nomebanco" type="hidden" class="vermelho" id="nomebanco" value="" size="70"/>
  <input type="hidden" name="MM_insert" value="form1">
</form>
<hr size="1" width="500" align="left" />
<form method="post" action="<%=MM_editAction%>" name="form2" enctype="multipart/form-data" onSubmit="document.form1.submit()">
  <table width="900">
    <tr>
      <td width="180" align="right" class="simples">Documento:</td>
      <td><input name="file" type="file" class="simples" onChange="javascript:nomeArquivo(this.value)" value="" size="70"></td>
    </tr>
    <tr>
      <td align="center">&nbsp;</td>
      <td><input name="submit" type="submit" class="simples" value="Inserir" onClick="return enviardados();" /> 
      <input name="Reset" type="reset" class="simples" value="Limpar" /></td>
    </tr>
  </table>  
</form>
<p>&nbsp;</p>
<p><a href="admin_menu.jsp" class="simples">.:.. voltar</a></p>
</div>
<jsp:include page="i_base.jsp" flush="true" />
</body>
</html>
<%
ultimo_arquivo.close();
Statementultimo_arquivo.close();
Connultimo_arquivo.close();
%>
Criado 4 de agosto de 2009
Ultima resposta 5 de ago. de 2009
Respostas 3
Participantes 2