ファイル名とクライアントからの他の値を読み取ることができません。私はHttpWebRequestを使用して、マルチパートデータをサーバーに送信しています。私のクライアント側のコードはそうのようになります。httpリクエストヘッダーからファイル名を読み取ることができません
public string upload(string file, string url)
{
HttpWebRequest requestToServer = (HttpWebRequest)
WebRequest.Create(url);
// Define a boundary string
string boundaryString = "----";
// Turn off the buffering of data to be written, to prevent
// OutOfMemoryException when sending data
requestToServer.AllowWriteStreamBuffering = false;
// Specify that request is a HTTP post
requestToServer.Method = WebRequestMethods.Http.Post;
// Specify that the content type is a multipart request
requestToServer.ContentType
= "multipart/form-data; boundary=" + boundaryString;
// Turn off keep alive
requestToServer.KeepAlive = false;
ASCIIEncoding ascii = new ASCIIEncoding();
string boundaryStringLine = "\r\n--" + boundaryString + "\r\n";
byte[] boundaryStringLineBytes = ascii.GetBytes(boundaryStringLine);
string lastBoundaryStringLine = "\r\n--" + boundaryString + "--\r\n";
byte[] lastBoundaryStringLineBytes = ascii.GetBytes(lastBoundaryStringLine);
NameValueCollection nvc = new NameValueCollection();
nvc.Add("id", "TTR");
// Get the byte array of the myFileDescription content disposition
string myFileDescriptionContentDisposition = Java.Lang.String.Format(
"Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}",
"myFileDescription",
"A sample file description");
byte[] myFileDescriptionContentDispositionBytes
= ascii.GetBytes(myFileDescriptionContentDisposition);
string fileUrl = file;
// Get the byte array of the string part of the myFile content
// disposition
string myFileContentDisposition = Java.Lang.String.Format(
"Content-Disposition: form-data;name=\"{0}\"; "
+ "filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n",
"myFile", Path.GetFileName(fileUrl), Path.GetExtension(fileUrl));
byte[] myFileContentDispositionBytes =
ascii.GetBytes(myFileContentDisposition);
var name = Path.GetFileName(fileUrl);
FileInfo fileInfo = new FileInfo(fileUrl);
// Calculate the total size of the HTTP request
long totalRequestBodySize = boundaryStringLineBytes.Length * 2
+ lastBoundaryStringLineBytes.Length
+ myFileDescriptionContentDispositionBytes.Length
+ myFileContentDispositionBytes.Length
+ fileInfo.Length;
// And indicate the value as the HTTP request content length
requestToServer.ContentLength = totalRequestBodySize;
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
// Write the http request body directly to the server
using (Stream s = requestToServer.GetRequestStream())
{
//foreach (string key in nvc.Keys)
//{
// s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
// string formitem = string.Format(formdataTemplate, key, nvc[key]);
// byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
// s.Write(formitembytes, 0, formitembytes.Length);
//}
// Send the file description content disposition over to the server
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileDescriptionContentDispositionBytes, 0,
myFileDescriptionContentDispositionBytes.Length);
// Send the file content disposition over to the server
s.Write(boundaryStringLineBytes, 0, boundaryStringLineBytes.Length);
s.Write(myFileContentDispositionBytes, 0,
myFileContentDispositionBytes.Length);
// Send the file binaries over to the server, in 1024 bytes chunk
FileStream fileStream = new FileStream(fileUrl, FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
s.Write(buffer, 0, bytesRead);
} // end while
fileStream.Close();
// Send the last part of the HTTP request body
s.Write(lastBoundaryStringLineBytes, 0, lastBoundaryStringLineBytes.Length);
WebResponse response = requestToServer.GetResponse();
StreamReader responseReader = new StreamReader(response.GetResponseStream());
string replyFromServer = responseReader.ReadToEnd();
return replyFromServer;
}
}
クライアント側で記述されているコンテンツ配置値は、サーバー側で取得されていません。サーバー側では、ファイル名は「{0}」として読み取られ、その後、他の値は「{1}」および「{2}」として読み取られます。
私のサーバー側のコードはそうのようになります。
public async Task<HttpResponseMessage> UploadFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var httpRequest = HttpContext.Current.Request;
var id = httpRequest.Form["{0}"];
var id2 = httpRequest.Form[0];
var s = id;
var l = id2;
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData file in provider.FileData)
{
Trace.WriteLine(file.Headers.ContentDisposition.FileName);
Trace.WriteLine("Server file path: " + file.LocalFileName);
}
if (httpRequest.Files.Count > 0)
{
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
// NOTE: To store in memory use postedFile.InputStream
}
return Request.CreateResponse(HttpStatusCode.Created);
}
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
私は2日間、この上で立ち往生してきた、それは狂気私を運転です。私は切り刻んだし、私のコードをいくつか変更しましたが、毎回違う問題があります。これは、サーバー上でヘッダーを正しく読み取ることを除いて、自分のコードを作成するために最も近いところです。
私は永遠に私を助けてくれる人に感謝します。
なぜJava.Lang.String.Formatを使用しますか?代わりに.NET String.Formatを使用してください。 – Evk
@Evkご返信ありがとうございます。それが潜在的に問題になる可能性があります。私はその行を変更し、それが本当に問題だった –
が動作するかどうかを確認します。私の質問に答えることができますので、私はあなたの答えを受け入れることができますか? :) –