接口的写法
HttpPostedFile file = null;
foreach (string upload in Request.Files.AllKeys)
{
if (Request.Files[upload] == null)
{
continue;
}
else
{
file = Request.Files[upload];
string filename = DateTime.Now.ToString("yyyyMMddHHmmssfffffff").ToString() + ".xlsx";// file.FileName.ToString();
string uploadPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\文件名1\\文件名2\\";
if (!Directory.Exists(uploadPath)) //引用磁盘上的现有目录
{
Directory.CreateDirectory(uploadPath);
}
string saveFile = uploadPath + filename; //保存文件的路径+文件名
file.SaveAs(saveFile);
}
}
接下来看看前端怎么写 (框架用 饿了么 + vue2.0 )
①最简单写法
<el-form ref="searchForm" :inline="true" :model="searchForm" class="mt-search-form" method="post" name="fileinfo" id="fileinfo">
<input type="file" ref="fileInput" style="display:none" @change="selectedFile">
<div class="toolItem" @click="clickUpload">
<p>上传文件</p>
</div>
<el-col>
<div class="grid-content bg-purple">
<label class="control-label" style="width: 125px;">
审批项目文件:
</label>
<div class="controls" style="margin-left: 0px;">
<input type="file" id="filepath" name="filepath" style="display:none" @change="changetext()" />
<input class="m-wrap" type="text" id="pathfile" name="pathfile" readonly="readonly" value="$filepath$" />
<input class="btn green" type="button" value="选择文件" id="uploadpath" />
</div>
</div>
</el-col>
<input class="btn blue" type="button" id="btnsubmit" value="提交" @click="update()" data-dismiss="modal" />
</el-form>
//上传图片
update: function () {
var pathfile = $("#pathfile").val();
var filepath = $("#filepath").val();
var formData = new FormData();
formData.append("filepath", filepath);
//FormData对象用以将数据编译成键值对,以便用XMLHttpRequest来发送数据
$.ajax({
url: "http://huangchaoqing.com",
type: "post",
data: formData,
contentType: false,
processData: false,
success: function (res) {
console.log('上传文件:', res);
if (res.Success) {
console.log('上传文件:', res.Data);
that.$refs.fileInput.value = '';
that.$message({
type: "success",
message: '上传成功',
showClose: true
});
that.getList();
} else {
that.$message({
type: "warning",
message: '上传失败,请刷新重试',
showClose: true
});
}
}
})
},
② 第二种样式写法
<div class="mt-upload_wrapper mt-row_layout">
<label for="" class="mt-upload_label">选择xlsx文件</label>
<el-upload class="mt-upload mt-row_layout" action="" :file-list="uploadedFileList" :on-change="changeUploadedFile" :auto-upload="false" ref="upload">
<el-button slot="trigger" size="small" type="">选择文件</el-button>
<span v-if="!uploadedFileList.length" class="el-upload__tip mt-upload_tip" slot="tip">未选择任何文件</span>
</el-upload>
</div>
定义下 uploadedFileList: [], 上传的文件列表
formData.append("FileData", self.uploadedFileList[0].raw);