在这里,我为这个表单数据传递 API 创建了一个小演示。现在我正在使用邮递员检查此 API,但我没有收到任何数据。
代码
const http = require("http");
const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(
bodyParser.json({
limit: "50mb"
})
);
app.use(
bodyParser.urlencoded({
limit: "50mb",
extended: true
})
);
app.post('/form-data', (req, res) => {
console.log("form-data ->> ", req.body)
});
server = http.createServer(app);
server.listen(4000[![enter image description here][1]][1], () => {
console.log(`Server started`);
});
Run Code Online (Sandbox Code Playgroud)
服务器日志
Server started
form-data ->> {}
Run Code Online (Sandbox Code Playgroud)
我正在使用 fastify-multer 和 JSON Schema 提交可能包含文件的多部分表单数据。无论我做什么,Fastify 总是给我一个错误的响应错误:
{
"statusCode": 400,
"error": "Bad Request",
"message": "body must be object"
}
Run Code Online (Sandbox Code Playgroud)
这是我的index.ts:
const server = fastify();
server.register(require("@fastify/cors"));
server.register(multer.contentParser).after(() => {
if (!isProdEnv) {
server.register(require("@fastify/swagger"), {
/* ... */
});
}
server.register(require("@fastify/auth")).after(() => {
server.decorate("authenticateRequest", authenticateRequest);
server.decorate("requireAuthentication", requireAuthentication);
server.addHook("preHandler", server.auth([server.authenticateRequest]));
server.register(indexRouter);
server.register(authRouter, { prefix: "/auth" });
server.register(usersRouter, { prefix: "/users" });
server.register(listsRouter, { prefix: "/lists" });
server.register(postsRouter, { prefix: "/posts" });
server.register(searchRouter, { prefix: "/search" });
server.register(settingsRouter, { prefix: "/settings" }); …Run Code Online (Sandbox Code Playgroud) 我在将 blob 附加到 FormData 时遇到了一个奇怪的问题。根据文档(https://developer.mozilla.org/en-US/docs/Web/API/FormData/append),追加函数可以是 String 或 Blob。我的代码是这样的:
const blobFromSync = (...args) =>
import('node-fetch').then(({ blobFromSync }) => blobFromSync(...args));
let file_location = '/path/to/video/file.mp4';
const file = await blobFromSync(file_location);
const chunkSize = 40000;
for (let start = 0; start < file.size; start += chunkSize) {
const chunk = file.slice(start, start + chunkSize + 1)
const form = new FormData();
form.append('file', chunk, 'an-id');
}
Run Code Online (Sandbox Code Playgroud)
控制台记录该块显示它是一个 Blob,但它会抛出此错误:
TypeError: source.on is not a function
at DelayedStream.create (/Users/xxxxxxxxx/Development/terminal-backend/node_modules/delayed-stream/lib/delayed_stream.js:33:10)
at CombinedStream.append (/Users/xxxxxxx/Development/terminal-backend/node_modules/combined-stream/lib/combined_stream.js:45:37)
at FormData.append (/Users/xxxxxxxxx/Development/terminal-backend/node_modules/form-data/lib/form_data.js:75:3) …Run Code Online (Sandbox Code Playgroud) 我正在使用上传文件,jQuery.ajax并且除了Internet Explorer 10之外,一切在Google Chrome,Mozilla Firefox,Opera等现代浏览器中都很完美.
new FormData($('.uploadForm')[0])在IE10中不起作用,但如果我只尝试使用这段代码:new FormData($('.uploadForm'))它可以工作......看起来它不接受特定索引处的元素或其他东西?我不明白这真的很好,这就是为什么我在寻求帮助的原因.
IE10的这个例子是否存在任何变通方法?
JS:
var form = new FormData($('.uploadForm')[0]);
config.progressBar.progressWidth = 0;
$('.uploadForm .valueBox').fadeOut('slow',function(){
$(this).addClass('hidden')
$('.meter').removeClass('hidden').width(config.progressBar.width);
$.ajax({
url: '../../uploads/some.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.onprogress = progress;
}
return myXhr;
},
success: function (res) {
console.log(res)
},
data: form,
cache: false,
contentType: false,
processData: false
});
Run Code Online (Sandbox Code Playgroud)
some.php代码和平:
foreach($_FILES["file"]["error"] as $key => $value) {
if ($value == UPLOAD_ERR_OK){
$name = $_FILES["file"]["name"][$key];
$arr_files = getimagesize($_FILES["file"]["tmp_name"][$key]); …Run Code Online (Sandbox Code Playgroud) 我在MVC 4中遇到了一个场景,我需要在ajax调用中发送一个图像以及对象列表.我如何在formData中附加它?这是我的formdata和ajax调用
var formdata = new FormData();
var imgFile = document.getElementById('ProfilePic');
var imgfileList = imgFile.files;
formdata.append(imgfileList[0].name, imgfileList[0]);
// Below Code is not workin
formdata.append('Rent', $scope.RentTypes);
// $scope.RentType = [{ id:1,price:5},{id:2,price:6}]
$.ajax({
url: url
data: formdata,
processData: false,
contentType: false,
type: 'POST'
});
Run Code Online (Sandbox Code Playgroud)
在控制器中,从ajax调用调用的动作就是这样
public ActionResult Upload(List<Rent> Rent)
{
}
Run Code Online (Sandbox Code Playgroud)
Rent.cs
public class Rent
{
public int id;
public int price;
public Available;
}
Run Code Online (Sandbox Code Playgroud) 我可以访问服务器,但无法发布表单数据。我应该如何通过https请求发布表单数据?我正在使用表单数据库中的表单数据,并使用https请求进行邮寄。当我运行以下代码时,我可以访问该服务,但是该服务给出的响应是未提交表单数据。
var https = require('https');
var FormData = require('form-data');
//var querystring = require('querystring');
var fs = require('fs');
var form = new FormData();
connect();
function connect() {
username = "wr";
password = "45!"
var auth = 'Basic ' + new Buffer(username + ':' + password).toString('base64');
var options = {
hostname: 'trans/sun.com',
port: 443,
path: '/transfer/upload-v1/file',
method: 'POST',
rejectUnauthorized: false,
headers: {
'Authorization': auth,
'Content-Type': 'application/json',
//'Content-Length': postData.length
}
};
form.append('deviceId', '2612');
form.append('compressionType', 'Z');
form.append('file', fs.createReadStream('/Mybugs.txt'));
var req = https.request(options, function(res) { …Run Code Online (Sandbox Code Playgroud) FormData对于具有2个输入字段的表单,对象为空。formData.getAll()记录错误TypeError: Not enough arguments to FormData.getAll.。这是我的代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script>
function test () {
var element = document.getElementById("invite-form");
console.log(element);
var formdata = new FormData(element)
console.log(formdata.getAll());
}
</script>
</head>
<body>
<form id="invite-form" method='POST' action=''>
<label for="email">Email...</label>
<input type="text" name="email" value="human@earth.com"/>
<input type="hidden" name="csrf_token" value="random" />
<button class="btn" onclick="test()">Button</button>
</form>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
我尝试FormData在单击按钮时使用表单中的值填充对象
我目前正在使用 React Native 0.48 和 react-native-image-crop-picker 0.16。
我正在尝试获取文件 uri,并使用 FormData 和 Fetch 将其发送到服务器。
这是我正在做的代码片段:
var image = await ImagePicker.openPicker({
width: 500,
height: 500,
cropping: true,
includeBase64: true,
});
var media = {
uri: image.path,
type: 'image/jpeg',
name: 'file.jpg',
};
var formData = new FormData();
formData.append("file", media);
fetch("https://requestb.in/1e6lgdo1", {
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formData
}).then(function(r){
console.log("Success", r);
}).catch(function(e){
console.log("Error", e);
}).done();
Run Code Online (Sandbox Code Playgroud)
不幸的是,当请求被发送到服务器而不是发送“文件”表单数据字段中的文件内容时,它只是发送“[对象对象]”。
根据您将请求发送到的位置,这会导致文件内容变为“[object Object]”或请求出错。
我无法确定这是我自己的代码的问题,还是本机本身的反应。任何帮助将不胜感激。
我正在为我的测试服务器使用https://github.com/jpillora/uploader。(注意:Go 在字符串化对象时从不使用符号 [object Object],所以我不认为问题出在服务器上。此外,我在将文件上传到 S3 时也看到了这一点。)
一个最终被发送的请求的例子是:
------WebKitFormBoundaryzt2jTR8Oh7dXB56z
Content-Disposition: …Run Code Online (Sandbox Code Playgroud) 我想上传一些文件,但是当我使用axios发布时,我的formdata在laravel中是一个空请求
vuejs:uploader.vue
filesChange(e) {
const fileList = e.target.files;
const formData = new FormData();
if (!fileList.length) return;
for (let i = 0; i < fileList.length; i += 1) {
console.log(fileList[i]);
formData.append('files', fileList[i], fileList[i].name);
}
this.save(formData);
},
Run Code Online (Sandbox Code Playgroud)
save(formData) {
photosApi.storePhotos(formData, this.galleryId).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error);
});
},
Run Code Online (Sandbox Code Playgroud)
vuejs:photosApi.js
storePhotos(formData, id) {
return axios.post(`api/photo/${id}`, formData);
},
Run Code Online (Sandbox Code Playgroud)
laravel:api.php
Route::post('/photo/{id}', 'PhotoController@store');
Run Code Online (Sandbox Code Playgroud)
laravel:PhotoController.php
public function store(Request $request, $id)
{
return $request->all();
}
Run Code Online (Sandbox Code Playgroud)
我在做什么错?
我有一个 react native 项目,它从文本输入接收姓名、电子邮件、电话号码,然后将这些数据插入到 php 服务器 throw fetch api 并且它工作正常,但我需要让用户能够上传图像,当点击保存按钮时,所有数据(姓名,电子邮件,电话号码,照片)保存到php服务器抛出api,现在我使用“react-native-image-picker”并且工作正常但我不知道如何使用表单数据上传带有数据抛出api的图像.
这是反应本机代码:
import React, { Component } from 'react';
import {View,Text,StyleSheet,TextInput,TouchableOpacity,Image} from 'react-native';
import ViewDataUsers from './ViewDataUsers';
import ImagePicker from 'react-native-image-picker';
const options={
title:'select a photo',
takePhotoButtonTitle:'Take a Photo',
chooseFrmoLibraryButtonTitle:'Choose from Gallery',
quality:1
};
class InputUsers extends Component{
//constructor have a state that conatains the properties that will recieve the values from Text Inputes
constructor(props){
super(props)
this.state = {
TextInputName:'',
TextInputEmail:'',
TextInputPhoneNumber:'',
iamgeSource: null,
}
}
selectPhoto(){
ImagePicker.showImagePicker(options, (response) => { …Run Code Online (Sandbox Code Playgroud)