forked from anjoy8/Blog.Core
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathImgController.cs
More file actions
106 lines (92 loc) · 3.03 KB
/
ImgController.cs
File metadata and controls
106 lines (92 loc) · 3.03 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Blog.Core.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace Blog.Core.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ImgController : Controller
{
// GET: api/Img
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET: api/Img/5
[HttpGet("{id}", Name = "Get")]
public string Get(int id)
{
return "value";
}
[HttpPost]
[Route("Pic")]
public async Task<MessageModel<string>> InsertPicture([FromServices]IHostingEnvironment environment)
{
var data = new MessageModel<string>();
string path = string.Empty;
string foldername = "images";
var files = Request.Form.Files;
if (files == null || files.Count() <= 0) { data.Msg = "请选择上传的文件。"; return data; }
//格式限制
var allowType = new string[] { "image/jpg", "image/png", "image/jpeg" };
string folderpath = Path.Combine(environment.WebRootPath, foldername);
if (!System.IO.Directory.Exists(folderpath))
{
System.IO.Directory.CreateDirectory(folderpath);
}
if (files.Any(c => allowType.Contains(c.ContentType)))
{
if (files.Sum(c => c.Length) <= 1024 * 1024 * 4)
{
//foreach (var file in files)
var file = files.FirstOrDefault();
string strpath = Path.Combine(foldername, DateTime.Now.ToString("MMddHHmmss") + file.FileName);
path = Path.Combine(environment.WebRootPath, strpath);
using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
await file.CopyToAsync(stream);
}
data = new MessageModel<string>()
{
Response = strpath,
Msg = "上传成功",
Success = true,
};
return data;
}
else
{
data.Msg = "图片过大";
return data;
}
}
else
{
data.Msg = "图片格式错误";
return data;
}
}
// POST: api/Img
[HttpPost]
public void Post([FromBody] object formdata)
{
}
// PUT: api/Img/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}