I have to a web services method called uploadFile.the method getting a parameter as base64str and record as a file into the specified address it.
But,I have a problem.That method doesn't allow to upload more than 350 KB file.Otherwise,I can upload less than 300 KB file e.g zip, jpg, txt. Also,
When I attempt to upload more than 350 KB file,a process working continually on server.
Process:
Image Name : w3wp.exe, UserName : ASP.Net v4.0, CPU : 50, Description : IIS Worker Process
Sometimes server cpu goes to 100%
Code:
* encodedFile = Base64Str as format
string postString = string.Format("userName={0}&userVendor={1}&vendorKey={2}&base64FileStr={3}&guid={4}&fileName={5}", "kadi", "şifre", "key", encodedFile, guid, strFilename);
string localHttpPostUrl = userGatewayAddress + "uploadFile";
ASCIIEncoding encoding = new ASCIIEncoding();
Stream newStream = null;
HttpWebResponse response = null;
Stream streamResponse = null;
StreamReader streamRead = null;
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(localHttpPostUrl);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
byte[] buffer = Encoding.UTF8.GetBytes(postString);
request.ContentLength = buffer.Length;
newStream = request.GetRequestStream();
newStream.Write(buffer, 0, buffer.Length);
newStream.Close();
response = (HttpWebResponse)request.GetResponse();
streamResponse = response.GetResponseStream();
streamRead = new StreamReader(streamResponse);
Char[] readBuffer = new Char[256];
ret = string.Empty;
int totalCharCount = 0;
int count = streamRead.Read(readBuffer, 0, 256);
while (count > 0)
{
totalCharCount += count;
ret += new String(readBuffer);
count = streamRead.Read(readBuffer, 0, 256);
}
ret = ret.Substring(0, totalCharCount);
return ret;
}
catch (Exception x)
{
return x.Message;
}
<system.web>
<!-- 100 KB Max POST size -->
<httpRuntime maxRequestLength="100"/>
</system.web>
http://support.microsoft.com/kb/832878
Related
I have a method that uploads files to our server. I'm seeing the error in the title when trying to upload a large file. I've tried increasing maxRequestLength from 35480 KB in web.config but I'm still seeing the error.
<httpRuntime maxRequestLength="3548000" executionTimeout="1000" targetFramework="4.6.1"/>
I've also tried making the request within a using statement as mentioned in this post System.Net.ProtocolViolationException: You must write ContentLength bytes to the request stream before calling [Begin]GetResponse to no avail. Any advice would be appreciated.
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("--"); sb.Append(boundary); sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\""); sb.Append(fileFormName);
sb.Append("\"; filename=\""); sb.Append(Path.GetFileName(uploadfile)); sb.Append("\""); sb.Append("\r\n");
sb.Append("Content-Type: "); sb.Append("application/octet-stream"); sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = System.Text.Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array. ensuring the boundary appears on a line by itself
byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
string strRead = "";
FileStream fileStream = null;
Stream requestStream = null;
WebResponse responce = null;
StreamReader responseStream = null;
try
{
fileStream = new FileStream(uploadfile, FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length + boundaryBytes.Length;
webrequest.ContentLength = length;
using (requestStream = webrequest.GetRequestStream())
{
//requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); }
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
responce = webrequest.GetResponse();
}
responseStream = new StreamReader(responce.GetResponseStream());
strRead = responseStream.ReadToEnd();
}
catch (Exception ex)
{
// handle error
}
finally
{
if( fileStream != null ) fileStream.Close();
if( requestStream != null ) requestStream.Close();
if( responseStream != null ) responseStream.Close();
if( responce != null ) responce.Close();
}
return strRead;
This was solved by setting maxAllowedContentLength in system.webServer. Maximum request length exceeded.
How I can send XML to a web service from C#(.NET)?
Not using "add references"
And I want get response from the service
This code has no exceptions, but I think app can't autorize in web service
I do so
class Program
{
static void Main(string[] args)
{
string xml = "<message>"+
"<service id="+"single"+" source = "+"AlphaName"+"/>"+
"<to>number</to>"+
"<body content-type="+"text/plain"+">"+
"This is a sample message"+
"</body>"+
"</message>";
Program prog = new Program();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://api.life.com.ua/ip2sms/");
request.Credentials = new NetworkCredential("login", "password");
byte[] authBytes = Encoding.UTF8.GetBytes("login:password".ToCharArray());
request.Headers["Authorization"] = Convert.ToBase64String(authBytes);
prog.requests(xml);
}
}
XML request
String requests(string xml)
{
WebResponse result = null;
WebRequest req = null;
Stream newStream = null;
Stream ReceiveStream = null;
StreamReader sr = null;
string strOut = "";
try
{
req = WebRequest.Create("https://api.life.com.ua/ip2sms/");
req.Method = "POST";
req.Timeout = 120000;
//req.ContentType = "text/xml; charset = \"utf8\"";
req.ContentType = "application/x-www-form-urlencoded";
byte[] SomeBytes = null;
SomeBytes = UTF8Encoding.UTF8.GetBytes(xml);
req.ContentLength = SomeBytes.Length;
newStream = req.GetRequestStream();
newStream.Write(SomeBytes, 0, SomeBytes.Length);
newStream.Close();
// считываем результат работы
result = req.GetResponse();
ReceiveStream = result.GetResponseStream();
Encoding encode = Encoding.UTF8;
sr = new StreamReader(ReceiveStream, encode);
Char[] read = new Char[256];
int count = sr.Read(read, 0, 256);
while (count > 0)
{
String str = new String(read, 0, count);
strOut += str;
count = sr.Read(read, 0, 256);
}
}
catch (Exception ex)
{
}
return strOut;
}
but nothing happens.Thanks!
I'm trying to set up a web api service that searches for a .pdf file in a directory and returns the file if it's found.
The controller
public class ProductsController : ApiController
{
[HttpPost]
public HttpResponseMessage Post([FromBody]string certificateId)
{
string fileName = certificateId + ".pdf";
var path = #"C:\Certificates\20487A" + fileName;
//check the directory for pdf matching the certid
if (File.Exists(path))
{
//if there is a match then return the file
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var stream = new FileStream(path, FileMode.Open);
stream.Position = 0;
result.Content = new StreamContent(stream);
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = fileName };
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf");
result.Content.Headers.ContentDisposition.FileName = fileName;
return result;
}
else
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.Gone);
return result;
}
}
}
I'm calling the service with the following code
private void GetCertQueryResponse(string url, string serial)
{
string encodedParameters = "certificateId=" + serial.Replace(" ", "");
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";
httpRequest.AllowAutoRedirect = false;
byte[] bytedata = Encoding.UTF8.GetBytes(encodedParameters);
httpRequest.ContentLength = bytedata.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(bytedata, 0, bytedata.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)httpRequest.GetResponse();
if (response.StatusCode == HttpStatusCode.OK)
{
byte[] bytes = null;
using (Stream stream = response.GetResponseStream())
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
byte[] buf = new byte[1024];
count = stream.Read(buf, 0, 1024);
ms.Write(buf, 0, count);
} while (stream.CanRead && count > 0);
ms.Position = 0;
bytes = ms.ToArray();
}
var filename = serial + ".pdf";
Response.ContentType = "application/pdf";
Response.Headers.Add("Content-Disposition", "attachment; filename=\"" + filename + "\"");
Response.BinaryWrite(bytes);
}
}
This appears to be working in the sense that the download file dialogue is shown with the correct file name and size etc, but the download takes only a couple of seconds (when the file sizes are >30mb) and the files are corrupt when I try to open them.
Any ideas what I'm doing wrong?
Your code looks similar to what Ive used in the past, but below is what I typically use:
Response.AddHeader("content-length", myfile.Length.ToString())
Response.AddHeader("content-disposition", "inline; filename=MyFilename")
Response.AddHeader("Expires", "0")
Response.AddHeader("Pragma", "Cache")
Response.AddHeader("Cache-Control", "private")
Response.ContentType = "application/pdf"
Response.BinaryWrite(finalForm)
I post this for 2 reasons. One, add the content-length header, you may have to indicate how large the file is so the application waits for the whole response.
If that doesn't fix it. Set a breakpoint, does the byte array content the appropriate length (aka, 30 million bytes for a 30 MB file)? Have you used fiddler to see how much content is coming back over the HTTP call?
I can upload file to google drive from my website, but my problem is it will show the file as Untitled after uploading.
How can I add or post title to the uploading file.
Thanks,
My Code:
public string UploadFile(string accessToken, byte[] file_data, string mime_type)
{
try
{
string result = "";
byte[] buffer = file_data;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.googleapis.com/upload/drive/v2/files?uploadType=media");
request.Method = "POST";
request.ContentType = mime_type;
request.ContentLength = buffer.Length;
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + accessToken);
var stream = request.GetRequestStream();
stream.Write(file_data, 0, file_data.Length);
stream.Close();
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();//Get error here
if(webResponse.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = webResponse.GetResponseStream();
StreamReader responseStreamReader = new StreamReader(responseStream);
result = responseStreamReader.ReadToEnd();//parse token from result
var jLinq = JObject.Parse(result);
JObject jObject = JObject.Parse(jLinq.ToString());
webResponse.Close();
return jObject["alternateLink"].ToString();
}
return string.Empty;
}
catch
{
return string.Empty;
}
}
I used RestSharp for uploading a file to google drive.
public static void UploadFile(string accessToken, string parentId)
{
var client = new RestClient { BaseUrl = new Uri("https://www.googleapis.com/") };
var request = new RestRequest(string.Format("/upload/drive/v2/files?uploadType=multipart&access_token={0}", accessToken), Method.POST);
var bytes = File.ReadAllBytes(#"D:\mypdf.pdf");
var content = new { title = "mypdf.pdf", description = "mypdf.pdf", parents = new[] { new { id = parentId } }, mimeType = "application/pdf" };
var data = JsonConvert.SerializeObject(content);
request.AddFile("content", Encoding.UTF8.GetBytes(data), "content", "application/json; charset=utf-8");
request.AddFile("mypdf.pdf", bytes, "mypdf.pdf", "application/pdf");
var response = client.Execute(request);
if (response.StatusCode != HttpStatusCode.OK) throw new Exception("Unable to upload file to google drive");
}
Doing it with out using the google.apis dlls isnt that easy. You need to send the meta data before you send the rest of the file. For that you need to use uploadType=multipart
https://developers.google.com/drive/manage-uploads#multipart
This should get you started sorry its a wall of code. I havent had time to create a tutorial for this yet.
FileInfo info = new FileInfo(pFilename);
//Createing the MetaData to send
List<string> _postData = new List<string>();
_postData.Add("{");
_postData.Add("\"title\": \"" + info.Name + "\",");
_postData.Add("\"description\": \"Uploaded with SendToGoogleDrive\",");
_postData.Add("\"parents\": [{\"id\":\"" + pFolder + "\"}],");
_postData.Add("\"mimeType\": \"" + GetMimeType(pFilename).ToString() + "\"");
_postData.Add("}");
string postData = string.Join(" ", _postData.ToArray());
byte[] MetaDataByteArray = Encoding.UTF8.GetBytes(postData);
// creating the Data For the file
byte[] FileByteArray = System.IO.File.ReadAllBytes(pFilename);
string boundry = "foo_bar_baz";
string url = "https://www.googleapis.com/upload/drive/v2/files?uploadType=multipart" + "&access_token=" + myAutentication.accessToken;
WebRequest request = WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "multipart/related; boundary=\"" + boundry + "\"";
// Wrighting Meta Data
string headerJson = string.Format("--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
"application/json; charset=UTF-8");
string headerFile = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n",
boundry,
GetMimeType(pFilename).ToString());
string footer = "\r\n--" + boundry + "--\r\n";
int headerLenght = headerJson.Length + headerFile.Length + footer.Length;
request.ContentLength = MetaDataByteArray.Length + FileByteArray.Length + headerLenght;
Stream dataStream = request.GetRequestStream();
dataStream.Write(Encoding.UTF8.GetBytes(headerJson), 0, Encoding.UTF8.GetByteCount(headerJson)); // write the MetaData ContentType
dataStream.Write(MetaDataByteArray, 0, MetaDataByteArray.Length); // write the MetaData
dataStream.Write(Encoding.UTF8.GetBytes(headerFile), 0, Encoding.UTF8.GetByteCount(headerFile)); // write the File ContentType
dataStream.Write(FileByteArray, 0, FileByteArray.Length); // write the file
// Add the end of the request. Start with a newline
dataStream.Write(Encoding.UTF8.GetBytes(footer), 0, Encoding.UTF8.GetByteCount(footer));
dataStream.Close();
try
{
WebResponse response = request.GetResponse();
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
//Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
return "Exception uploading file: uploading file." + ex.Message;
}
If you need any explinations beyond the comments let me know. I strugled to get this working for a month. Its almost as bad as resumable upload.
I was searching for the solution of the given problem and previously I was putting uploadType=resumable that causes the given issue and when I used uploadType=multipart problem is resolved...
I am trying to download file from a file hosting server, using my username and password through my own website.
I already achieve the possibility to connect and download the file, with the code attached below.
my problem is this code doesn't support resume of download and my download manager isn't able to open more then one connection to the remote site ,so the speed is very low(the remote site Of course is supporting those features)
my main goal is to let me download this file with full speed and with the ability to resume the download in any Second.
this is the code
//the login method
ASCIIEncoding encoding = new ASCIIEncoding();
string url = "RemoteServerLoginPage/loginPage";
string postVariables = "id=myIdToTheServer";
postVariables += "&password=MyPasswordToTheServer";
// create the POST request
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
CookieContainer cookies = new CookieContainer();
webRequest.CookieContainer = cookies;
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = postVariables.Length;
byte[] data = encoding.GetBytes(postVariables);
Stream newStream = webRequest.GetRequestStream();
// Send the request
newStream.Write(data, 0, data.Length);
HttpWebResponse resp = (HttpWebResponse)webRequest.GetResponse();
using (Stream stream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
//after login get the file with thr right cookies
string url2 = "UrlOfRemoteServerFileAdress/filename.rar";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url2);
req.CookieContainer = cookies;
HttpWebResponse resp2 = (HttpWebResponse)req.GetResponse();
////Initialize the output stream
Response.Clear();
Response.AppendHeader("Content-Disposition:", "attachment; filename=myfile.rar");
Response.AppendHeader("Content-Length:", "bytes");
Response.AppendHeader("Connection:", "Keep-Alive");
Response.ContentType = "application/octet-stream";
Response.AppendHeader("AcceptRanges", resp2.ContentLength.ToString());
const int BufferLength = 4 * 1024 * 1024;
byte[] byteBuffer = new byte[BufferLength];
Stream rs = req.GetResponse().GetResponseStream();
int len = 0;
while ((len = rs.Read(byteBuffer, 0, byteBuffer.Length)) > 0)
{
if (len < BufferLength)
{
Response.BinaryWrite(byteBuffer.Take(len).ToArray());
}
else
{
Response.BinaryWrite(byteBuffer);
}
Response.Flush();
}