我尝试使用Jquery和POST方法将图像和一些输入上传到服务器。我试过这段代码但它给我的错误: POST 500(内部服务器错误)。 有人可以帮我弄清楚代码有什么问题。谢谢你的帮助。
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
fd.append("label", "WEBUPLOAD");
$.ajax({
url: "http://URL?api_token=fb24085da58dad6decb9271fb170ef2ed8c80617",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();">
<label>Select a file:</label><br>
<input type="file" name="file" required />
<input type="text" name="text" required />
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
</body>
</html>
&#13;
当debuging停止在这部分时,似乎问题是来自客户端,因为在服务器中需要图像,所以它不能为空,这就是他抛出错误的原因。 :
答案 0 :(得分:2)
您需要为您的html表单指定enctype="multipart/form-data"
属性。
答案 1 :(得分:2)
这是正确的代码,只需要更改服务器的URL即可。感谢user1080381,他在评论中给了我解决方案。
<!DOCTYPE html>
<html>
<head>
<title>Image Upload Form</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function submitForm() {
console.log("submit event");
var fd = new FormData(document.getElementById("fileinfo"));
console.log(fd);
//fd.append("label", "WEBUPLOAD");
console.log(fd);
$.ajax({
url: "http://TypeYourURL?api_token=fb24085da58dad6decb9271fb170ef2ed8c80617",
type: "POST",
data: fd,
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function( data ) {
console.log("PHP Output:");
console.log( data );
});
return false;
}
</script>
</head>
<body>
<form method="post" id="fileinfo" name="fileinfo" onsubmit="return submitForm();" enctype="multipart/form-data">
<label>Select a file:</label><br>
<input type="file" name="img" required />
<input type="text" name="name" required />
<input type="submit" value="Upload" />
</form>
<div id="output"></div>
</body>
</html>