文件上传问题
发布于 6 年前 作者 zimulili 3009 次浏览 来自 问答

**1.**HTML form表单提交

<form action="/" method="POST" enctype="multipart/form-data">
  <div class="form-group">
    <label for="exampleInputFile">File input</label>
    <input type="file" id="image" name="imgfile">
    <p class="help-block">text here.</p>
  </div>
  <button type="submit" id="submit" class="btn btn-default">Submit</button>
</form>
后台没有接收到file

2.$.ajax()

前端代码:
let formdata = new FormData()
formdata.append('file', $('#image')[0].files[0])
$.ajax({
  url: '/',
  type: 'post',
  data: formdata,
  processData: false,
  success: function (result) {
    console.log(result)
  }
})
后台代码:
const formidable = require('formidable');
router.post('/', checkLogIn, function (req, res, next) {
	let form = new formidable.IncomingForm()
	form.parse(req, function(err, fields, files){
		console.log(files)
		res.send('///////////////')
	})
})
后台也没有接收到files

3. xhr

前端代码:
	let formdata = new FormData()
	formdata.append('file', $('#image')[0].files[0])
	let xhr = new XMLHttpRequest()
	xhr.open('post', '/poolimg', true)
	xhr.send(formdata)
	xhr.onload = function() {
		console.log(xhr.response)
	}
后台代码:
const formidable = require('formidable');
router.post('/', checkLogIn, function (req, res, next) {
	let form = new formidable.IncomingForm()
	form.parse(req, function(err, fields, files){
		console.log(files)
		res.send('///////////////')
	})
})

后台能接收到files

为什么会这样呢?

6 回复

自己在浏览器对比看一下请求嘛。

jQuery 的请求中,加一个 contentType: false

表达提交本来就会发请求,你又自己发ajax。发ajax这时的content-type可能不对

楼上分析的对的

@Choicelin 我当然是分别测试的呀,form不行我才用的ajax,ajax也不行我才用的XHLHttpRequest呀,ajax的contentType: false也用了,我就想知道为什么会这样

你的基础需要补补,content-type是传mime类型,然后你说的xhrhttprequest跟ajax是一个什么关系,你需要自己研究一下

回到顶部