原文: i.jakeyu.top/2017/01/10/…
作者: Jake
FormData
物件使用一些鍵值對來模擬一個完整的表單,然後使用ajax傳送這個FormData
物件,後端便可以拿到表單中上傳的檔案。
前端處理
HTML程式碼
<form>
<input type="file" id="uploadFile" name="file">
</form>複製程式碼
如果只想上傳圖片:
<input id="uploadFile" type="file" name="file" accept="image/png,image/gif"/>複製程式碼
可配置屬性:
- accept:表示可以選擇的檔案MIME型別,多個MIME型別用英文逗號分開,常用的MIME型別見下表。
- multiple:是否可以選擇多個檔案,多個檔案時其value值為第一個檔案的虛擬路徑。
常用MIME型別
字尾名 | MIME名稱 |
---|---|
*.3gpp | audio/3gpp, video/3gpp |
*.ac3 | audio/ac3 |
*.asf | allpication/vnd.ms-asf |
*.au | audio/basic |
*.css | text/css |
*.csv | text/csv |
*.doc | application/msword |
*.dot | application/msword |
*.dtd | application/xml-dtd |
*.dwg | image/vnd.dwg |
*.dxf | image/vnd.dxf |
*.gif | image/gif |
*.htm | text/html |
*.html | text/html |
*.jp2 | image/jp2 |
*.jpe | image/jpeg |
*.jpeg | image/jpeg |
*.jpg | image/jpeg |
*.js | text/javascript, application/javascript |
*.json | application/json |
*.mp2 | audio/mpeg, video/mpeg |
*.mp3 | audio/mpeg |
*.mp4 | audio/mp4, video/mp4 |
*.mpeg | video/mpeg |
*.mpg | video/mpeg |
*.mpp | application/vnd.ms-project |
*.ogg | application/ogg, audio/ogg |
application/pdf | |
*.png | image/png |
*.pot | application/vnd.ms-powerpoint |
*.pps | application/vnd.ms-powerpoint |
*.ppt | application/vnd.ms-powerpoint |
*.rtf | application/rtf, text/rtf |
*.svf | image/vnd.svf |
*.tif | image/tiff |
*.tiff | image/tiff |
*.txt | text/plain |
*.wdb | application/vnd.ms-works |
*.wps | application/vnd.ms-works |
*.xhtml | application/xhtml+xml |
*.xlc | application/vnd.ms-excel |
*.xlm | application/vnd.ms-excel |
*.xls | application/vnd.ms-excel |
*.xlt | application/vnd.ms-excel |
*.xlw | application/vnd.ms-excel |
*.xml | text/xml, application/xml |
*.zip | aplication/zip |
*.xlsx | application/vnd.openxmlformats-officedocument.spreadsheetml.sheet |
javascript程式碼
$('#uploadFile').on('change',function(e){
var file = this.files[0];
var formData = new FormData();
formData.append('file',file);
$.ajax({
url: '/webgl/upload/zip',
type: 'post',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(res){
//
}
})
})複製程式碼
這裡我是在檔案被選擇上傳後就會立即觸發ajax
上傳檔案事件,而表單中其他欄位我沒有使用FormData
物件,所以<form>
標籤沒有新增enctype="multipart/form-data"
屬性。
注:
processData
設定為false
。因為data
值是FormData
物件,不需要對資料做處理。cache
設定為false
,上傳檔案不需要快取。contentType
設定為false
。
nodejs程式碼
multer模組
我使用了multer
模組,更多資訊。初始化multer
模組配置
var storageZip = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'public/uploads/zip') //檔案儲存路徑
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.zip') //對檔案重新命名,防止檔名衝突
}
})
var uploadZip = multer({
storage: storageZip
});複製程式碼
路由配置
app.post('/webgl/upload/zip', uploadZip.single('file'), function(req, res) {
res.json(req.file)
})複製程式碼
- 這裡
single()
引數名就是使用FormData.append()
方法新增時的檔名,這裡我用的是file
。 - 上傳結束之後,會把
file
物件返回給前端,file
物件會包含檔名等資訊。