IdHTTPServer1 收到POST 文件和参数

使用INDY 10 ,不然有些单元可能无法找到编译。

目前发现的问题有:对于#$0A 会自动转变成 #$0D#$0A,在传输文件时最好是进行编码传输。网上搜索这类信息很少,好像是Decoder.ReadBody 问题,传文本文件之类的一切正常。留着以前再改进吧。

uses
  Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
  System.Classes, Vcl.Graphics,
  Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IdContext, IdCustomHTTPServer,
  IdBaseComponent, IdComponent, IdCustomTCPServer, IdHTTPServer, IdHeaderList,
  idGlobal,
  IdIntercept, IdMessage, IdMessageCoderMIME, IdMessageCoder, IdGlobalProtocols;


procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext;

  ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
Var
  ms: TMemoryStream;
  newdecoder, Decoder: TIdMessageDecoder;
  boundary, startboundary: String;
  msgEnd: Boolean;
  tmp: String;
  I: Integer;
  fname: String;
  tsValues: TStringList;


begin
  I := 0;

  if pos('upload', lowercase(ARequestInfo.Document)) > 0 then
  begin
    If ARequestInfo.PostStream = nil then

      AResponseInfo.ContentText := '<HTML><BODY>unparsed:' +
        ARequestInfo.UnparsedParams + '<br>Encoding:' +
        ARequestInfo.ContentEncoding + ARequestInfo.RawHeaders.Values
        ['Content-Type'] + '<br>HashCode:' + IntToStr(ARequestInfo.GetHashCode)
        + '<br>Params:' + ARequestInfo.Params.Text +
        ' -->stream nullo<br></BODY><HTML>'
    Else
      ARequestInfo.PostStream.Position := 0;
    msgEnd := False;


    boundary := ExtractHeaderSubItem(ARequestInfo.ContentType, 'boundary',
      QuoteHTTP);
    startboundary := '--' + boundary;
    repeat
      tmp := ReadLnFromStream(ARequestInfo.PostStream, -1, True);
    until tmp = startboundary;


    Decoder := TIdMessageDecoderMIME.Create(nil);
    TIdMessageDecoderMIME(Decoder).MIMEBoundary := boundary;
    tsValues := TStringList.Create;


    try
      repeat
        Decoder.SourceStream := ARequestInfo.PostStream;
        Decoder.FreeSourceStream := False;
        Decoder.ReadHeader;
        inc(I);
        case Decoder.PartType of
          mcptAttachment, mcptText:
            begin
              ms := TMemoryStream.Create;
              ms.Position := 0;
              newdecoder := Decoder.ReadBody(ms, msgEnd);
              tmp := Decoder.Headers.Text;
              fname := Decoder.Filename;
              Decoder.Free;
              Decoder := newdecoder;
              if Decoder <> nil then
                TIdMessageDecoderMIME(Decoder).MIMEBoundary := boundary;
              sleep(100);
              if fname <> '' then
              begin
                ms.SaveToFile(fname);
                // msgEnd := true;
              end
              else
              begin
                ms.SaveToFile(IntToStr(I) + '.txt');
              end;
              ms.Free;
            end;
          mcptIgnore:
            Begin
              try
                FreeAndNil(Decoder);
                Decoder := TIdMessageDecoderMIME.Create(nil);
                TIdMessageDecoderMIME(Decoder).MIMEBoundary := boundary;
              finally
                ms.Free;
              end;
            End;
          mcptEOF:
            begin
              FreeAndNil(Decoder);
              msgEnd := True
            end;
        end;


      until (Decoder = nil) or (msgEnd);
    finally
      if Decoder <> nil then
        Decoder.Free;


    end;


    AResponseInfo.ContentText := AResponseInfo.ContentText + '</BODY><HTML>';

    AResponseInfo.ContentText := '<HTML><BODY>unparsed:' +
      ARequestInfo.UnparsedParams + '<br>Encoding:' +
      ARequestInfo.ContentEncoding + '<br>Conte' +
      ARequestInfo.RawHeaders.Values['Content-Type'] + '<br>HashCode:' +
      IntToStr(ARequestInfo.GetHashCode) + '<br>Params:' +
      ARequestInfo.Params.Text + ' -->stream nullo<br></BODY><HTML>';
  end
  Else
  Begin              //
    AResponseInfo.ContentText :=
      '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">   '
      + #10#13 +
      '<html xmlns="http://www.w3.org/1999/xhtml">                                                                                 '
      + #10#13 +
      '<head>                                                                                                                      '
      + #10#13 +
      '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />                                                       '
      + #10#13 +
      '<title>上传测试</title>                                                                                               '
      + #10#13 +
      '</head>                                                                                                                     '
      + #10#13 +
      '                                                                                                                            '
      + #10#13 +
      '<body>                                                                                                                      '
      + #10#13 +
      '<h1>测试多字段提交 </h1> <BR><BR>                                                        '
      + #10#13 +
      '<form action="upload" method="post"  enctype="multipart/form-data">                                                                                               '
      + #10#13 +
      '<p>key                                                                                                                      '
      + #10#13 +
      '  <input type="text" name="key" id="key" />                                                                                 '
      + #10#13 +
      '</p>                                                                                                                        '
      + #10#13 +
      '<p>group                                                                                                                      '
      + #10#13 +
      '  <input type="text" name="group" id="key" />                                                                                 '
      + #10#13 +
      '</p>                                                                                                                        '
      + #10#13 +
      '                                                                                                                            '
      + #10#13 +
      '<label for="file">文件:</label>                                                                                         '
      + #10#13 + '<label for="file">' + ARequestInfo.Document +
      '</label>                                                                                         '
      + #10#13 +
      '<input type="file" name="file" id="file" />                                                                                 '
      + #10#13 +
      '<br />                                                                                                                      '
      + #10#13 +
      '<input type="submit" name="submit" value="Submit" />                                                                        '
      + #10#13 +
      '</form></p>                                                                                                                  '
      + #10#13 +
      '</body>                                                                                                                     '
      + #10#13 +
      '</html>                                                                                                                     ';
  End;


end;
在 Java 中发送 POST 请求并携带文件参数,你可以使用 `java.net.HttpURLConnection` 类来实现。下面是一个示例代码: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class FileUploadExample { public static void main(String[] args) throws IOException { String url = "http://example.com/upload"; // 请求的URL String filePath = "/path/to/file"; // 文件路径 String paramName = "file"; // 文件参数名 String paramName2 = "param1"; // 其他参数名 String paramValue2 = "value1"; // 其他参数值 File file = new File(filePath); URL requestUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) requestUrl.openConnection(); // 设置请求方法为POST connection.setRequestMethod("POST"); connection.setDoOutput(true); // 设置请求头部信息 connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"); try (OutputStream outputStream = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream))) { // 写入文件参数 writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"" + paramName + "\"; filename=\"" + file.getName() + "\"\r\n") .append("Content-Type: " + HttpURLConnection.guessContentTypeFromName(file.getName()) + "\r\n") .append("\r\n") .flush(); // 写入文件内容 try (InputStream inputStream = new FileInputStream(file)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); } // 写入其他参数 writer.append("\r\n") .append("------WebKitFormBoundary7MA4YWxkTrZu0gW\r\n") .append("Content-Disposition: form-data; name=\"" + paramName2 + "\"\r\n") .append("\r\n") .append(paramValue2) .append("\r\n") .flush(); // 结束标记 writer.append("------WebKitFormBoundary7MA4YWxkTrZu0gW--\r\n").flush(); } // 发送请求并获取响应 int responseCode = connection.getResponseCode(); System.out.println("Response Code: " + responseCode); try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; StringBuilder response = new StringBuilder(); while ((line = reader.readLine()) != null) { response.append(line); } System.out.println("Response: " + response.toString()); } } } ``` 在上面的示例代码中,我们首先创建了一个 `HttpURLConnection` 对象,并设置请求方法为 POST,然后设置请求头部信息。接下来,我们使用输出流向服务器写入请求体内容,首先是文件参数,然后是文件内容,最后是其他参数。发送请求后,我们可以获取响应的状态码和响应内容。 请注意,示例中的边界字符串 `"----WebKitFormBoundary7MA4YWxkTrZu0gW"` 只是一个示例,请根据实际情况修改该字符串。 希望这可以帮助到你!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值