簡體   English   中英

有沒有辦法將 PowerShell 中的文件上傳到 rest api

[英]Is there a way to upload file in PowerShell to rest api

我正在尋找一種將帶有 Powershell 的文件上傳到用 Python 編寫的 api 的方法。

服務器端: import os from flask import Flask, jsonify, request, abort, flash, redirects import, url_for from werkze secure

UPLOAD_FOLDER = 'd:/Temp/11aa/'
ALLOWED_EXTENSIONS = {'jpg'}
app = Flask(__name__)



def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS

@app.route('/attachmnt', methods=['GET', 'POST'])
def upload_file():

    if request.method == 'POST':
        if 'file' not in request.files:
            flash('No file part')
            return redirect(request.url)
        file = request.files['file']
        # if user does not select file, browser also
        # submit an empty part without filename
        if file.filename == '':
            flash('No selected file')
            return redirect(request.url)
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return redirect(url_for('uploaded_file',
                                    filename=filename))
    return '''
    <!doctype html>
    <title>Upload new File</title>
    <h1>Upload new File</h1>
    <form method=post enctype=multipart/form-data>
      <input type=file name=file>
      <input type=submit value=Upload>
    </form>
    '''




if __name__ == '__main__':
    app.secret_key = 'pwd'
    app.run(debug=True)

來自 Powershell 的請求:

Invoke-WebRequest -uri 'http://127.0.0.1:5000/attachmnt' -Method Post -Infile "./test.jpg"  -ContentType 'image/jpg'  -UseDefaultCredentials 

Invoke-RestMethod 是用於 Rest 的更謹慎的 cmldet,因為這是它的目的。

調用-RestMethod | 微軟文檔

  • 模塊:Microsoft.PowerShell.Utility
  • 向 RESTful web 服務發送 HTTP 或 HTTPS 請求。

PowerShell 的 Invoke-RestMethod 的簡單示例

簡單的 GET 示例

$response = Invoke-RestMethod 'http://example.com/api/people'
# assuming the response was in this format { "items": [] }
# we can now extract the child people like this
$people = $response.items

帶有自定義標頭的 GET 示例

$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("X-DATE", '9/29/2014')
$headers.Add("X-SIGNATURE", '234j123l4kl23j41l23k4j')
$headers.Add("X-API-KEY", 'testuser')

$response = Invoke-RestMethod 'http://example.com/api/people/1' -Headers $headers

PUT/POST 示例

$person = @{
    first='joe'
    lastname='doe'
}
$json = $person | ConvertTo-Json
$response = Invoke-RestMethod 'http://example.com/api/people/1' -Method Put -Body $json -ContentType 'application/json'

刪除示例

$response = Invoke-RestMethod 'http://example.com/api/people/1' -Method Delete

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM