Ir para conteúdo
Fórum Script Brasil
  • 0

Upload no formulário


Vagner Nunes

Pergunta

Prezados,

Nos sites que faço sempre utilizado um formulário para enviar dados ao banco e outro formulário para gravar as imagens fazendo upload.

Os senhores poderiam me ajudar, queria inserir o dados e o upload em um formulário só.

Abaixo um formulário que geralmente uso.

Obrigado pela ajuda

Sds,

<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!--#include file="Connections/Conn.asp" -->
<%
' *** Edit Operations: declare variables

Dim MM_editAction
Dim MM_abortEdit
Dim MM_editQuery
Dim MM_editCmd

Dim MM_editConnection
Dim MM_editTable
Dim MM_editRedirectUrl
Dim MM_editColumn
Dim MM_recordId

Dim MM_fieldsStr
Dim MM_columnsStr
Dim MM_fields
Dim MM_columns
Dim MM_typeArray
Dim MM_formVal
Dim MM_delim
Dim MM_altVal
Dim MM_emptyVal
Dim MM_i

MM_editAction = CStr(Request.ServerVariables("SCRIPT_NAME"))
If (Request.QueryString <> "") Then
  MM_editAction = MM_editAction & "?" & Server.HTMLEncode(Request.QueryString)
End If

' boolean to abort record edit
MM_abortEdit = false

' query string to execute
MM_editQuery = ""
%>
<%
' *** Insert Record: set variables

If (CStr(Request("MM_insert")) = "form1") Then

  MM_editConnection = MM_Conn_STRING
  MM_editTable = "chamada"
  MM_editRedirectUrl = "Relacionamento 2008/processo/sucess.asp"
  MM_fieldsStr  = "curso1|value|curso2|value|data|value|email|value|fonte|value|hora|value|idade|value|informacao|value|motivo|value|municipio|value|nome|value|provedor|value|qual|value|telefone|value"
  MM_columnsStr = "curso1|',none,''|curso2|',none,''|data|',none,NULL|email|',none,''|fonte|',none,''|hora|',none,NULL|idade|',none,''|informacao|',none,''|motivo|',none,''|municipio|',none,''|nome|',none,''|provedor|',none,''|qual|',none,''|telefone|',none,''"

  ' create the MM_fields and MM_columns arrays
  MM_fields = Split(MM_fieldsStr, "|")
  MM_columns = Split(MM_columnsStr, "|")
  
  ' set the form values
  For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
    MM_fields(MM_i+1) = CStr(Request.Form(MM_fields(MM_i)))
  Next

  ' append the query string to the redirect URL
  If (MM_editRedirectUrl <> "" And Request.QueryString <> "") Then
    If (InStr(1, MM_editRedirectUrl, "?", vbTextCompare) = 0 And Request.QueryString <> "") Then
      MM_editRedirectUrl = MM_editRedirectUrl & "?" & Request.QueryString
    Else
      MM_editRedirectUrl = MM_editRedirectUrl & "&" & Request.QueryString
    End If
  End If

End If
%>
<%
' *** Insert Record: construct a sql insert statement and execute it

Dim MM_tableValues
Dim MM_dbValues

If (CStr(Request("MM_insert")) <> "") Then

  ' create the sql insert statement
  MM_tableValues = ""
  MM_dbValues = ""
  For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
    MM_formVal = MM_fields(MM_i+1)
    MM_typeArray = Split(MM_columns(MM_i+1),",")
    MM_delim = MM_typeArray(0)
    If (MM_delim = "none") Then MM_delim = ""
    MM_altVal = MM_typeArray(1)
    If (MM_altVal = "none") Then MM_altVal = ""
    MM_emptyVal = MM_typeArray(2)
    If (MM_emptyVal = "none") Then MM_emptyVal = ""
    If (MM_formVal = "") Then
      MM_formVal = MM_emptyVal
    Else
      If (MM_altVal <> "") Then
        MM_formVal = MM_altVal
      ElseIf (MM_delim = "'") Then  ' escape quotes
        MM_formVal = "'" & Replace(MM_formVal,"'","''") & "'"
      Else
        MM_formVal = MM_delim + MM_formVal + MM_delim
      End If
    End If
    If (MM_i <> LBound(MM_fields)) Then
      MM_tableValues = MM_tableValues & ","
      MM_dbValues = MM_dbValues & ","
    End If
    MM_tableValues = MM_tableValues & MM_columns(MM_i)
    MM_dbValues = MM_dbValues & MM_formVal
  Next
  MM_editQuery = "insert into " & MM_editTable & " (" & MM_tableValues & ") values (" & MM_dbValues & ")"

  If (Not MM_abortEdit) Then
    ' execute the insert
    Set MM_editCmd = Server.CreateObject("ADODB.Command")
    MM_editCmd.ActiveConnection = MM_editConnection
    MM_editCmd.CommandText = MM_editQuery
    MM_editCmd.Execute
    MM_editCmd.ActiveConnection.Close

    If (MM_editRedirectUrl <> "") Then
      Response.Redirect(MM_editRedirectUrl)
    End If
  End If

End If
%>
<%
Dim Gravar
Dim Gravar_numRows

Set Gravar = Server.CreateObject("ADODB.Recordset")
Gravar.ActiveConnection = MM_Conn_STRING
Gravar.Source = "SELECT * FROM chamada"
Gravar.CursorType = 0
Gravar.CursorLocation = 2
Gravar.LockType = 1
Gravar.Open()

Gravar_numRows = 0
%>
<!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>Untitled Document</title>
</head>

<body>
<form action="<%=MM_editAction%>" method="POST" enctype="multipart/form-data" name="form1">
  <table align="center">
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Curso1:</div></td>
      <td><div align="left">
        <input type="text" name="curso1" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Curso2:</div></td>
      <td><div align="left">
        <input type="text" name="curso2" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Data:</div></td>
      <td><div align="left">
        <input type="text" name="data" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Email:</div></td>
      <td><div align="left">
        <input type="text" name="email" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Fonte:</div></td>
      <td><div align="left">
        <input type="text" name="fonte" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Hora:</div></td>
      <td><div align="left">
        <input type="text" name="hora" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Idade:</div></td>
      <td><div align="left">
        <input type="text" name="idade" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Informacao:</div></td>
      <td><div align="left">
        <input type="text" name="informacao" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Motivo:</div></td>
      <td><div align="left">
        <input type="text" name="motivo" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Municipio:</div></td>
      <td><div align="left">
        <input type="text" name="municipio" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Nome:</div></td>
      <td><div align="left">
        <input type="text" name="nome" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Provedor:</div></td>
      <td><div align="left">
        <input type="text" name="provedor" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Qual:</div></td>
      <td><div align="left">
        <input type="text" name="qual" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Telefone:</div></td>
      <td><div align="left">
        <input type="text" name="telefone" value="" size="32">      
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Foto1</div></td>
      <td><div align="left">
        <label>
        <input name="foto1" type="file" id="foto1" />
        </label>
</div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right"><div align="left">Foto2</div></td>
      <td><div align="left">
        <input name="foto2" type="file" id="foto2" />
      </div></td>
    </tr>
    <tr valign="baseline">
      <td nowrap align="right">&nbsp;</td>
      <td><input type="submit" value="Cadastrar">      </td>
    </tr>
  </table>
  <input type="hidden" name="MM_insert" value="form1">
</form>
<p>&nbsp;</p>
</body>
</html>
<%
Gravar.Close()
Set Gravar = Nothing
%>

Link para o comentário
Compartilhar em outros sites

7 respostass a esta questão

Posts Recomendados

  • 0

Vagner... o seu código ta realmente uma bagunça... "Feio" por assim dizer...

quanto a utilizar um form só basta que você faça o form conforme necessário, e na página das actions desse form incluir os scripts necessários para executar todas as tarefas necessárias...

você pode por exemplo, ter dois inserts pra cada tabela, 3 consultas, dois deletes... enfim... só um exemplo... você pode ter o que você quiser... A construção disso é basicamente a mesma... você pega simplesmente e cola um codigo no outro... altera pequenos detalhes como nome de variáveis e etc...

No caso de um upload como o form precisa ser multpart, você precisará resgatar os dados desse form da mesma forma que resgata o nome do arquivo... Usando a sintaxe do componente upload e não os requests normais...

Mas em princípio é bem tranquilo... tem um ou dois detalhezinhos que você precisará arrumar... mas nada de mais...

Faça o que o Bareta sugeriu... de uma revisada no seu code... no seu html... ta bem bagunçadinho!

[]'s Rafael Spilki

Link para o comentário
Compartilhar em outros sites

  • 0

bom se eu estiver certo em relação ao componente mude

' set the form values
  For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
    MM_fields(MM_i+1) = CStr(Request.Form(MM_fields(MM_i)))
  Next
por
' set the form values
  For MM_i = LBound(MM_fields) To UBound(MM_fields) Step 2
    MM_fields(MM_i+1) = CStr(UploadFormRequest(MM_fields(MM_i)))
  Next

Link para o comentário
Compartilhar em outros sites

  • 0

Prezados,

Peço ajuda dos senhores novamente, estou a dias tentando fazer um upload pelo meu formulário, mas não estou conseguindo.

Alguém poderia me ajudar?

Tenho um formulário onde tenho campos nome, email, telefone, foto1 e foto2.

Gostaria que os campos foto1 e foto2 além de grava-los no banco a fazer upload ao mesmo tempo, mas não sei fazer este procedimento de gravar no banco e fazer upload.

Seria muito grato se alguém poder me ajudar.

Abaixo está o código do arquivo que faz Upload onde hospedo site.

<%
    Set Upload = Server.CreateObject("Persits.Upload.1")

    Upload.OverwriteFiles = False
    On Error Resume Next

    Upload.SetMaxSize 1048576    ' Limit files to 1MB
    Count = Upload.Save("E:\domains\j\jacaraipeonline.com\user\htdocs\qdelicia\uploads\")
%>
<html>
<body BGCOLOR="#FFFFFF">
<center>

<% If Err <> 0 Then %>

    <font SIZE=3 FACE="Arial" COLOR=#0020A0>
    <h3>Ocorreu um erro ao fazer o Upload:</h3>
    </font>

    <font SIZE=3 FACE="Arial" COLOR=#FF2020>
    <h2>"<% = Err.Description %>"</h2>
    </font>

    <font SIZE=2 FACE="Arial" COLOR="#0020A0">
    Please <a HREF="doces_teste.asp">try again</a>.
    </font>

<% Else %>
<font SIZE=3 FACE="Arial" COLOR=#0020A0>
<h2>Sucesso! <% = Count %> file(s) Arquivo carregado.</h2>
</font>

<font SIZE=3 FACE="Arial" COLOR=#0020A0>
<table BORDER=1 CELLPADDING=3 CELLSPACING=0>
<th BGCOLOR="#FFFF00">Uploaded File</th><th BGCOLOR="#FFFF00">Size</th><th BGCOLOR="#FFFF00">Original Size</th><tr>
<% For Each File in Upload.Files %>
<% If File.ImageType = "GIF" or File.ImageType = "JPG" or File.ImageType = "PNG" Then %>
        <td ALIGN=CENTER>
            <img SRC="/upload/<% = File.FileName%>"><br><b><% = File.OriginalPath%></b><br>
            (<% = File.ImageWidth %> x <% = File.ImageHeight %> pixels)
        
        </td>
    <% Else %>
        <td><b><% = File.OriginalPath %></b></td>
    <% End If %>
    <td ALIGN=RIGHT VALIGN="TOP"><% =File.Size %> bytes</td>
    <td ALIGN=RIGHT VALIGN="TOP"><% =File.OriginalSize %> bytes</td><tr>
<% Next %>
</table>
</font>
<p>
<font SIZE=2 FACE="Arial" COLOR=#0020A0>
Click <a HREF="doces.asp">here</a> to upload more files.</font>
<% End If %>

<hr>
<font SIZE=2 FACE="Arial" COLOR=#0020A0>
<a HREF="http://www.persits.com/aspupload.exe">Download</a> your trial copy of AspUpload.
</font>

Link para o comentário
Compartilhar em outros sites

  • 0

André, boa noite.

Por se tratar do mesmo assunto (posts iguais) e ainda não ter nenhuma resposta postada, tomei a liberdade de apagar o seu outro tópico. Cuide para não abrir tópicos iguais, ok?

No meu escritório tenho um script que faz isso que você quer, amanhã quando eu chegar vou dar uma espiadinha nele pra ver se consigo te dar uma luz, certinho?

Ó... mas esse html... aiaiaiai!!!

Volto a postar algo pela manhã!

[]'s Rafael Spilki

Link para o comentário
Compartilhar em outros sites

  • 0

Prezado Rafael,

Já dei uma limpeza em meu formulário e tá cadastrando, preciso de ajuda somente no Upload, e como fazer....

Trabalho na manutenção de dois site, e os dois usa componentes diferentes, que seria, o Dundas Upload e o ou é o Persits (eu acho que escreve assim).

Obrigado pela ajuda.....

Sds,

Vagner Nunes

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      651,9k
×
×
  • Criar Novo...