api上傳下載檔案

Posted by Leo Yang on 2023-11-22

上傳

後端API使用IFormFile做為參數把檔案送給API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public async Task<string> Upload([FromForm] IFormFile file)
{
....
//產生亂數資料夾名稱
string fileID = Guid.NewGuid().ToString("N");
//產生要放檔案的目錄
string fileDirectoryPath = System.IO.Path.Combine(MediaRootPath, "Upload", fileID);
//要放檔案的路徑
string fileFullPath = System.IO.Path.Combine(MediaRootPath, "Upload", fileID, file.FileName);

//建立亂數目錄
Directory.CreateDirectory(fileDirectoryPath);

//存檔
using (Stream fileStream = new FileStream(fileFullPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}

//API回傳結果給前端
UploadFileResponse responseObject = new UploadFileResponse();
responseObject.FileName = file.FileName;
responseObject.FileID = fileID;
response.Data = responseObject;
return JsonConvert.SerializeObject(response);
}

前端使用ajax呼叫webapi

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
form.append("file", document.getElementById("MainContent_fupFile").files[0]);
var settings = { "url": "<%=$"{System.Configuration.ConfigurationManager.AppSettings["WsWebAPI"]}FileUpload/UploadFile"%>",
"method": "POST",
"timeout": 0,
"processData": false,
"mimeType": "multipart/form-data",
"contentType": false,
"data": form
};
//上傳檔案的ID
var fileID = '';
//上傳檔案的檔名
var fileName = '';
//取得上傳檔案API回應結果
updateResult = $.ajax(settings).done(function (response)
{
var jsonObject = JSON.parse(response);
fileID = jsonObject.Data.FileID;
fileName = jsonObject.Data.FileName;
alert('上傳成功' + fileName + ', ' + fileID);
uploadSuccess = true;
});
//等待檔案上傳完成
$.when(updateResult).done(function ()
{
//do something
});

下載

前端呼叫API下載檔案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function Download(fileID, fileName)
{
var req = new XMLHttpRequest();
req.open("GET", "<%=$"{System.Configuration.ConfigurationManager.AppSettings["WsWebAPI"]}FileUpload/DownloadFile?fileID="%>" + fileID, true);
req.responseType = "blob";
req.onload = function (event)
{
var blob = req.response;
var link = document.createElement('a');
link.download = fileName;
link.href = window.URL.createObjectURL(blob);
link.click();
};

req.send();
}

後端下載檔案API

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public async Task<IActionResult> Download(string fileID)
{
//取得儲存檔案位置目錄
string MediaRootPath = _config.GetValue<string>("ApSetting:MediaRootPath") ?? string.Empty;

//取得檔案目錄
string fileDirectoryPath = System.IO.Path.Combine(MediaRootPath, "Upload", fileID);

//判斷上傳檔案的目錄是否存在
if (!Directory.Exists(fileDirectoryPath))
{
return NotFound();
}

//取出目錄中所有檔案
DirectoryInfo d = new DirectoryInfo(fileDirectoryPath);
FileInfo[] foundFiles = d.GetFiles();
if(foundFiles.Length == 0)
{
return NotFound();
}

//下載檔案
byte[] buffer;
FileStream fileStream = new FileStream(foundFiles[0].FullName, FileMode.Open, FileAccess.Read);
int length = (int)fileStream.Length;
buffer = new byte[length];
int count;
int sum = 0;
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
{
sum += count;
}
return File(buffer, "application/octet-stream", $"{{filename.ext}}");
}

前端使用boostrap datatable渲染資料

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var MasterTable;
MasterTable = $('#tableID').DataTable(
{
"processing": true,
"paging": true,
"searching": true,
"bFilter": false,
"bDestroy": true,
"scrollY": "455px",
"scrollCollapse": true,
"ajax": {
"url": 'apiurl',
"type": "POST",
"dataType": "json",
"data": { "MessgeType": "", "IsTop": "", "IsEnable": "" }
},
//定義欄位、title
"columns": [
{ "data": null, "title": "功能", "sWidth": "60px", "className": "myCenter" },
{ "data": "MessageNo", "title": "No", "sWidth": "50px", "className": "myCenter" },
{ "data": "MessgeType", "title": "訊息類型", "sWidth": "100px", "className": "myCenter" },
{ "data": "MessageTitle", "title": "訊息標題", "sWidth": "420px", "className": "myLeft" },
{ "data": "IsTop", "title": "TOP", "sWidth": "70px", "className": "myCenter" },
{ "data": "ExecuteStartDate", "title": "訊息啟用日期", "sWidth": "100px", "className": "myCenter" },
{ "data": "ExecuteEndDate", "title": "訊息結束日期", "sWidth": "100px", "className": "myCenter" },
{ "data": "IsEnable", "title": "啟用", "sWidth": "70px", "className": "myCenter" },
{ "data": "FileID", "title": "檔案", "sWidth": "70px", "className": "myCenter" }
],
//定義欄位渲染方式
columnDefs: [
{
targets: 0, render: function (data,display,object,position)
{
return '<button type=\'button\' class=\'btn btn-info btn-sm\' data-toggle=\'modal\' data-target=\'#exampleModal\' onclick="DataContent(\'' + object.MessageNo + '\')" >設定</button>';
}
},
{
targets: 8, render: function (data, display, object, position)
{
if (object.FileID == '')
return '<div>&nbsp;<div>';
else
return '<button type=\'button\' class=\'btn btn-info btn-sm\' onclick="Download(\'' + object.FileID + '\', \'' + object.FileName + '\')" >' + object.FileName + '</button>';

}
}],
order: [[1, "desc"]]
});

這樣就會長出一個表格,依照從api取得的資料渲染到表格裡面,其中index第0.8的欄位,會依照欄位定義的方式去渲染而不是單純顯示文字而已