C#webapiファイルストリームstreamの2つのアップロード方式「第1部分ファイルストリーム」
4680 ワード
ブログは仕事の勉強で出会った穴を記録するだけで、交流を歓迎します.
1.ファイルフロー
1.ファイルフロー
1.1クライアント
アップロードコンポーネントからInputStreamを取得しbyte[]に変換し、オブジェクトを組み立ててアップロードする
try{ byte[] buffer = new byte[filedata.InputStream.Length];
filedata.InputStream.Read(buffer, 0, buffer.Length);
var requstData = new
{
file = buffer,
path = resultPath,
fileName = filename
};
var result = UrlRequestHelper.HttpPostRequst(ConfigurationManager.AppSettings["FileUploadPath"], JsonConvert.SerializeObject(requstData), "");
}
httppost書き換え ///
/// post
///
///
///
public static string HttpPostRequst(string url, string postData, string ActionUrl)
{
byte[] bs = Encoding.UTF8.GetBytes(postData);
HttpWebRequest result = (HttpWebRequest)WebRequest.Create(url + ActionUrl);
result.ContentType = "application/json";
result.ContentLength = bs.Length;
result.Method = "POST";
using (Stream reqStream = result.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = result.GetResponse())
{
string reader = new StreamReader(wr.GetResponseStream(),
Encoding.UTF8).ReadToEnd();
return reader;
}
}
WebconfigのmaxRequestLengthの設定
1.2 webapi
受信最大値の設定
[FromBody]object bitで受信し、DeserializeObjectからオブジェクトを転送 [HttpPost]
public string FileUp([FromBody] object bit)
{
lock (_lock)
{
string jsonstr = JsonConvert.SerializeObject(bit);
Data res = JsonConvert.DeserializeObject(jsonstr);
return SaveFile(res.file, res.path, res.fileName);
}
}
ポイント:byte[]streamを転送し、ファイルに書き込む. private string SaveFile(byte[] file, string path, string fileName)
{
try
{
var serverPath = configPath; //
CreatePath(serverPath + @path);
var filename = fileName;
var filePath = string.Format(@"{0}\{1}", serverPath + @path, filename); //
var fullpath = filePath; //
//
using (var ms = new MemoryStream())
{
MemoryStream m = new MemoryStream(file);
string files = string.Format(@"{0}", fullpath);
FileStream fs = new FileStream(files, FileMode.OpenOrCreate);
m.WriteTo(fs);
m.Close();
fs.Close();
m = null;
fs = null;
return fullpath;
}
}
catch (Exception ex)
{
throw ex;
}
}
発生したピット:フォルダ権限の問題(発生しなかった場合は使用できません) ///
///
///
///
///
private void CreatePath(string filepath)
{
if (!Directory.Exists(filepath))
{
var securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(System.Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow));
Directory.CreateDirectory(filepath, securityRules);
}
}
勉強ノート!
try{ byte[] buffer = new byte[filedata.InputStream.Length];
filedata.InputStream.Read(buffer, 0, buffer.Length);
var requstData = new
{
file = buffer,
path = resultPath,
fileName = filename
};
var result = UrlRequestHelper.HttpPostRequst(ConfigurationManager.AppSettings["FileUploadPath"], JsonConvert.SerializeObject(requstData), "");
}
///
/// post
///
///
///
public static string HttpPostRequst(string url, string postData, string ActionUrl)
{
byte[] bs = Encoding.UTF8.GetBytes(postData);
HttpWebRequest result = (HttpWebRequest)WebRequest.Create(url + ActionUrl);
result.ContentType = "application/json";
result.ContentLength = bs.Length;
result.Method = "POST";
using (Stream reqStream = result.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse wr = result.GetResponse())
{
string reader = new StreamReader(wr.GetResponseStream(),
Encoding.UTF8).ReadToEnd();
return reader;
}
}
[HttpPost]
public string FileUp([FromBody] object bit)
{
lock (_lock)
{
string jsonstr = JsonConvert.SerializeObject(bit);
Data res = JsonConvert.DeserializeObject(jsonstr);
return SaveFile(res.file, res.path, res.fileName);
}
}
private string SaveFile(byte[] file, string path, string fileName)
{
try
{
var serverPath = configPath; //
CreatePath(serverPath + @path);
var filename = fileName;
var filePath = string.Format(@"{0}\{1}", serverPath + @path, filename); //
var fullpath = filePath; //
//
using (var ms = new MemoryStream())
{
MemoryStream m = new MemoryStream(file);
string files = string.Format(@"{0}", fullpath);
FileStream fs = new FileStream(files, FileMode.OpenOrCreate);
m.WriteTo(fs);
m.Close();
fs.Close();
m = null;
fs = null;
return fullpath;
}
}
catch (Exception ex)
{
throw ex;
}
}
///
///
///
///
///
private void CreatePath(string filepath)
{
if (!Directory.Exists(filepath))
{
var securityRules = new DirectorySecurity();
securityRules.AddAccessRule(new FileSystemAccessRule(System.Environment.UserName, FileSystemRights.FullControl, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
securityRules.AddAccessRule(new FileSystemAccessRule("NETWORK SERVICE", FileSystemRights.FullControl, AccessControlType.Allow));
Directory.CreateDirectory(filepath, securityRules);
}
}