force chrome to open downloaded pdf in a viewer - http

I have written the code for downloading a pdf file over http request.
public void downloadDocument(HttpServletRequest request,
HttpServletResponse response, #PathVariable("id") String docId)
throws Exception {
HttpSession session = request.getSession(true);
int accountId = (Integer) session.getAttribute("ownerAccountId");
Map<String, String> docMap = DbInteractor.getUploadedDocsByDocId(
Integer.valueOf(docId), accountId);
String docName = docMap.get("name");
String typeName = docMap.get("type");
String[] fileName = docName.split("\\.(?=[^\\.]+$)");
typeName= typeName.replace(" ", "");
if (typeName.equals("CCD/CCR")) {
typeName = "CCDorCCR";
}
String filename = typeName + docId + "." + fileName[1];
System.out.println(filename);
FileInputStream fileInputStream = new FileInputStream(
Constants.DOCUMENTS_PATH + filename);
response.setHeader("Expires", "0");
response.setHeader("Cache-Control",
"must-revalidate, post-check=0, pre-check=0");
response.setHeader("Content-disposition", "attachment; filename="
+ docName);
OutputStream os = response.getOutputStream();
IOUtils.copy(fileInputStream, os);
os.flush();
os.close();
}
But the file is getting automatically downloaded in chrome .Is there any way to force chrome to open this document in a viewer(or to ask for an open with dialog in chrome)

You are forcing the browser to download by sending "Content-Disposition: attachment".

Related

HTTP POST receiving more than one HTTP Response

I have an http POST being actioned via a .NET System.Net.WebRequest as follows:
...
XXXUtilities.Log.WriteLog(string.Format("XXXHTTPPost PostToUri has uri={0}, body={1}", uri, messageBodyAsString));
System.Net.WebRequest req = System.Net.WebRequest.Create(uri);
req.ContentType = "application/x-www-form-urlencoded";
req.Method = "POST";
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(messageBodyAsString);
req.ContentLength = bytes.Length;
System.IO.Stream os = req.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
try
{
using (System.Net.WebResponse resp = req.GetResponse())
{
if (resp == null) return null;
System.IO.StreamReader sr =
new System.IO.StreamReader(resp.GetResponseStream());
string rs = sr.ReadToEnd().Trim();
sr.Close();
resp.Close();
XXXUtilities.Log.WriteLog(string.Format("XXXHTTPPost PostToUri has string response = {0}", rs));
MongoDB.Bson.BsonDocument doc2 = new BsonDocument();
doc2.Add("Response", rs);
return doc2;
}
}
catch (System.Net.WebException e)
{...
This all works fine most of the time. However, looking at the log files that this creates I spotted something strange. The suspect log entries look like this:
18:59:17.0608 HPSHTTPPost PostToUri has uri=https://salesforce.ringlead.com/cgi-bin/2848/3/dedup.pl, body=LastName=Doe&FirstName=Jon
18:59:17.5608 HPSHTTPPost PostToUri has string response = Success
18:59:18.0295 HPSHTTPPost PostToUri has string response = Success
It seems that the Http Response is being received twice. Is this even technically possible? i.e. is it possible for an Http POST to receive two Responses, one after the other? If so, is my code below then liable to be called twice, thus resulting in the observed log file entries? Many thanks.
Edit:
In response to the comment that the logging code may be broken, here is the logging code:
public class Log
{
public static void WriteLog(string commandText)
{
string clientDBName = "test";
string username = "test";
try
{
string filePath = "c:\\Data\\XXXLogs\\" + clientDBName + "logs\\";
string filename = System.DateTime.Now.ToString("yyyyMMdd_") + username + ".log";
DirectoryInfo dir = new DirectoryInfo(filePath);
if (!dir.Exists)
{
dir.Create();
}
System.IO.FileStream stream = new System.IO.FileStream(
filePath + filename
, System.IO.FileMode.Append); // Will create if not already exists
StreamWriter writer = new StreamWriter(stream);
writer.WriteLine(); // Writes a line terminator, thus separating entries by 1 blank line
writer.WriteLine(System.DateTime.Now.ToString("HH:mm:ss.ffff") + " " + commandText);
writer.Flush();
stream.Close();
}
catch { }
}
}

How to force download a file from server in iphone browser

String filePath = "http://images.all-free-download.com/images
/graphiclarge/baby_child_girl_215819.jpg";
The above String is my download path.
URL url = new URL(filePath);
HttpURLConnection httpConn = (HttpURLConnection)
url.openConnection();
InputStream inStream = httpConn.getInputStream();
// if you want to use a relative path to context root:
#SuppressWarnings("unused")
String relativePath = getServletContext().getRealPath("");
// obtains ServletContext
ServletContext context = getServletContext();
// gets MIME type of the file
String mimeType = context.getMimeType(filePath);
if (mimeType == null) {
// set to binary type if MIME mapping not found
mimeType = "application/octet-stream";
}
// modifies response
response.setContentType(mimeType);
response.setContentLength((int) httpConn.getContentLength());
String fileName = filePath.substring(filePath.lastIndexOf("/") +
1,
filePath.length());
// forces download
//String headerKey = "Content-Disposition";
//String headerValue = String.format("attachment;
filename=\"%s\"", fileName);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment;
filename=\""+ fileName);
//response.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inStream.close();
outStream.close();
The above code working fine for android device in all browser. But its not working in iphone.
Once click download button, the image directly display. Not asking anythink.
I want store the image to gallary in iphone.
Can any one pls help me.Is it possible for iphone.

Problems with downloading copies of signed documents on my server through the docusign rest api

I am using docusign rest api in my asp.net mvc application. I uploaded a .docx file to docusign. After signing, i am downloading this file . It gets downloaded as .docx file itself. But not able to open it. When I open the same file with adobe reader, it can be opened as pdf file. Can anyone help me to download the signed document as pdf so that i can open it easily?
static string email = "****"; // your account email
static string password = "****"; // your account password
static string integratorKey = "******";
static string recipientName = "***";
static string documentName = "test1.docx";
static string baseURL = "";
public void UploadtoDocuSign(int DocId, string DocName, int ObjectTypeId, int ObjectId)
{
try
{
User _dealuser = _imanageVacancy.GetDealById(ObjectId).LeadUser;
string recipientName = _dealuser.FirstName + " " + _dealuser.LastName; // provide a recipient (signer's) name
string documentName = DocName;
string recipientEmail = _dealuser.EmailAddress;
string sectionname = "";
DocumentManager _docmanager = GetDocumentById(DocId);
if (_docmanager.SectionID != null)
sectionname = "\\" + GetSectionName_additionalDoc((int)_docmanager.SectionID);
string FileNameWithPath = CommonFunctions.ConfigReader.GetConfigValue("appSettings", "FileUploadPath") + "\\Documents\\" + EnumsNeeded.VacancySubMenu.Deal.ToString() + "\\" + ObjectId + sectionname + "\\" + documentName;
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Send Signature Request from Template
//============================================================================
/*
This is the only DocuSign API call that requires a "multipart/form-data" content type. We will be
constructing a request body in the following format (each newline is a CRLF):
--AAA
Content-Type: application/xml
Content-Disposition: form-data
<XML BODY GOES HERE>
--AAA
Content-Type:application/pdf
Content-Disposition: file; filename="document.pdf"; documentid=1
<DOCUMENT BYTES GO HERE>
--AAA--
*/
// append "/envelopes" to baseURL and use for signature request api call
url = baseURL + "/envelopes";
// construct an outgoing XML formatted request body (JSON also accepted)
// .. following body adds one signer and places a signature tab 100 pixels to the right
// and 100 pixels down from the top left corner of the document you supply
string xmlBody =
"<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<emailSubject>DocuSign API - Signature Request on Document</emailSubject>" +
"<status>sent</status>" + // "sent" to send immediately, "created" to save as draft in your account
// add document(s)
"<documents>" +
"<document>" +
"<documentId>1</documentId>" +
"<name>" + documentName + "</name>" +
"</document>" +
"</documents>" +
// add recipient(s)
"<recipients>" +
"<signers>" +
"<signer>" +
"<recipientId>1</recipientId>" +
"<email>" + recipientEmail + "</email>" +
"<name>" + recipientName + "</name>" +
"<tabs>" +
"<signHereTabs>" +
"<signHere>" +
"<xPosition>100</xPosition>" + // default unit is pixels
"<yPosition>100</yPosition>" + // default unit is pixels
"<documentId>1</documentId>" +
"<pageNumber>4</pageNumber>" +
"</signHere>" +
"</signHereTabs>" +
"</tabs>" +
"</signer>" +
"</signers>" +
"</recipients>" +
"</envelopeDefinition>";
// set request url, method, headers. Don't set the body yet, we'll set that separelty after
// we read the document bytes and configure the rest of the multipart/form-data request
request = initializeRequest(url, "POST", null, email, password);
// some extra config for this api call
configureMultiPartFormDataRequest(request, xmlBody, documentName, FileNameWithPath);
// read the http response
response = getResponseBody(request);
string envelopeId = parseDataFromResponse(response, "envelopeId");
_docmanager.DocuSignReferenceId = envelopeId;
_docmanager.DocuSignStatus = "Sent";
_iDocRep.Update(_docmanager);
_unitOfWork.Commit();
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
public void DocuSignDownload()
{
try
{
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Get Statuses of a set of envelopes
//============================================================================
//*** This example gets statuses of all envelopes in your account going back 1 month...
int curr_month = System.DateTime.Now.Month;
int curr_day = System.DateTime.Now.Day;
int curr_year = System.DateTime.Now.Year;
if (curr_month != 1)
{
curr_month -= 1;
}
else
{ // special case for january
curr_month = 12;
curr_year -= 1;
}
// append "/envelopes?from_date=MONTH/DAY/YEAR" and use in get statuses api call
// we need to URL encode the slash (/) chars, whos URL encoding is: %2F
url = baseURL + "/envelopes?from_date=" + curr_month.ToString() + "%2F" + curr_day.ToString() + "%2F" + curr_year.ToString();
// set request url, method, and headers. No request body for this api call...
request = initializeRequest(url, "GET", null, email, password);
// read the http response
response = getResponseBody(request);
string ComplenvIds = CompletedenvelopeIds(response);
ComplenvIds = ComplenvIds.TrimEnd(',');
string[] envIds = ComplenvIds.Split(',');
foreach (var envid in envIds)
{
DocumentManager _doc = _iDocRep.Get(x => x.DocuSignReferenceId == envid);
if (_doc != null)
{
DownloadCompletedEnvelopes(envid, _doc);
_doc.DocuSignStatus = "Completed";
_iDocRep.Update(_doc);
_unitOfWork.Commit();
}
}
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
public void DownloadCompletedEnvelopes(string envId, DocumentManager doc)
{
try
{
//============================================================================
// STEP 1 - Login API Call (used to retrieve your baseUrl)
//============================================================================
// Endpoint for Login api call (in demo environment):
string url = "https://demo.docusign.net/restapi/v2/login_information";
// set request url, method, and headers. No body needed for login api call
HttpWebRequest request = initializeRequest(url, "GET", null, email, password);
// read the http response
string response = getResponseBody(request);
// parse baseUrl from response body
baseURL = parseDataFromResponse(response, "baseUrl");
//============================================================================
// STEP 2 - Get Envelope Document(s) List and Info
//============================================================================
// append "/envelopes/{envelopeId}/documents" to to baseUrl and use for next endpoint
url = baseURL + "/envelopes/" + envId + "/documents";
//url = baseURL + "/envelopes/";
// set request url, method, body, and headers
request = initializeRequest(url, "GET", null, email, password);
// read the http response
response = getResponseBody(request);
// store each document name and uri locally, so that we can subsequently download each one
Dictionary<string, string> docsList = new Dictionary<string, string>();
string uri, name;
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopeDocument"))
{
XmlReader reader2 = reader.ReadSubtree();
uri = ""; name = "";
while (reader2.Read())
{
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "name"))
{
name = reader2.ReadString();
}
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "uri"))
{
uri = reader2.ReadString();
}
}// end while
docsList.Add(name, uri);
}
}
}
//============================================================================
// STEP 3 - Download the Document(s)
//============================================================================
//string envelopeID = "Some EnvelopeID";
//EnvelopePDF envPDF = apiService.RequestPDF(envelopeID);
foreach (KeyValuePair<string, string> kvp in docsList)
{
// append document uri to baseUrl and use to download each document(s)
url = baseURL + kvp.Value;
// set request url, method, body, and headers
request = initializeRequest(url, "GET", null, email, password);
request.Accept = "application/pdf"; // documents are converted to PDF in the DocuSign cloud
// read the response and store into a local file:
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
string sectionname = "";
if (doc.SectionID != null)
sectionname = "\\" + GetSectionName_additionalDoc((int)doc.SectionID);
using (MemoryStream ms = new MemoryStream())
using (FileStream outfile = new FileStream(CommonFunctions.ConfigReader.GetConfigValue("appSettings", "FileUploadPath") + "\\Documents\\" + EnumsNeeded.VacancySubMenu.Deal.ToString() + "\\" + doc.ObjectID + sectionname + "\\" + kvp.Key, FileMode.Create))
{
webResponse.GetResponseStream().CopyTo(ms);
if (ms.Length > int.MaxValue)
{
throw new NotSupportedException("Cannot write a file larger than 2GB.");
}
outfile.Write(ms.GetBuffer(), 0, (int)ms.Length);
}
}
Console.WriteLine("\nDone downloading document(s), check local directory.");
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
HttpWebResponse httpResponse = (HttpWebResponse)response;
Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
using (Stream data = response.GetResponseStream())
{
string text = new StreamReader(data).ReadToEnd();
}
}
}
}
//***********************************************************************************************
// --- HELPER FUNCTIONS ---
//***********************************************************************************************
public static HttpWebRequest initializeRequest(string url, string method, string body, string email, string password)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
addRequestHeaders(request, email, password);
if (body != null)
addRequestBody(request, body);
return request;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////
public static void addRequestHeaders(HttpWebRequest request, string email, string password)
{
// authentication header can be in JSON or XML format. XML used for this walkthrough:
string authenticateStr =
"<DocuSignCredentials>" +
"<Username>" + email + "</Username>" +
"<Password>" + password + "</Password>" +
"<IntegratorKey>" + integratorKey + "</IntegratorKey>" + // global (not passed)
"</DocuSignCredentials>";
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.Accept = "application/xml";
request.ContentType = "application/xml";
}
public static void addRequestBody(HttpWebRequest request, string requestBody)
{
// create byte array out of request body and add to the request object
byte[] body = System.Text.Encoding.UTF8.GetBytes(requestBody);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, requestBody.Length);
dataStream.Close();
}
public static void configureMultiPartFormDataRequest(HttpWebRequest request, string xmlBody, string docName, string FileNameWithPath)
{
// overwrite the default content-type header and set a boundary marker
request.ContentType = "multipart/form-data; boundary=BOUNDARY";
// start building the multipart request body
string requestBodyStart = "\r\n\r\n--BOUNDARY\r\n" +
"Content-Type: application/xml\r\n" +
"Content-Disposition: form-data\r\n" +
"\r\n" +
xmlBody + "\r\n\r\n--BOUNDARY\r\n" + // our xml formatted envelopeDefinition
"Content-Type: application/pdf\r\n" +
"Content-Disposition: file; filename=\"" + docName + "\"; documentId=1\r\n" +
"\r\n";
string requestBodyEnd = "\r\n--BOUNDARY--\r\n\r\n";
// read contents of provided document into the request stream
FileStream fileStream = System.IO.File.OpenRead(FileNameWithPath);
// write the body of the request
byte[] bodyStart = System.Text.Encoding.UTF8.GetBytes(requestBodyStart.ToString());
byte[] bodyEnd = System.Text.Encoding.UTF8.GetBytes(requestBodyEnd.ToString());
Stream dataStream = request.GetRequestStream();
dataStream.Write(bodyStart, 0, requestBodyStart.ToString().Length);
// Read the file contents and write them to the request stream. We read in blocks of 4096 bytes
byte[] buf = new byte[4096];
int len;
while ((len = fileStream.Read(buf, 0, 4096)) > 0)
{
dataStream.Write(buf, 0, len);
}
dataStream.Write(bodyEnd, 0, requestBodyEnd.ToString().Length);
dataStream.Close();
}
public static string getResponseBody(HttpWebRequest request)
{
// read the response stream into a local string
HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string responseText = sr.ReadToEnd();
return responseText;
}
public static string parseDataFromResponse(string response, string searchToken)
{
// look for "searchToken" in the response body and parse its value
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == searchToken))
return reader.ReadString();
}
}
return null;
}
public static string CompletedenvelopeIds(string response)
{
string compenvIds = "";
string envId = "";
// look for "searchToken" in the response body and parse its value
using (XmlReader reader = XmlReader.Create(new StringReader(response)))
{
while (reader.Read())
{
if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "envelopes"))
{
XmlReader reader2 = reader.ReadSubtree();
while (reader2.Read())
{
if ((reader2.NodeType == XmlNodeType.Element) && (reader2.Name == "envelope"))
{
XmlReader reader3 = reader2.ReadSubtree();
envId = "";
while (reader3.Read())
{
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "envelopeId"))
{
envId = reader3.ReadString();
}
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "status"))
{
if (reader3.ReadString() == "completed")
compenvIds = string.Concat(compenvIds, envId + ",");
}
if ((reader3.NodeType == XmlNodeType.Element) && (reader3.Name == "status"))
{
DateTime date = reader3.ReadContentAsDateTime();
}
}
}
}
}
}
}
return compenvIds;
}
public List<Lookup> LookupCache()
{
List<Lookup> _lookup = (List<Lookup>)HttpContext.Current.Cache["Lookup"];
if (HttpContext.Current.Cache["Lookup"] == null)
_lookup = _imanageUser.UpdateCache();
return _lookup;
}
string GetSectionName_additionalDoc(int SectionId)
{
List<Lookup> _lookup = LookupCache();
string _section = _lookup.Find(x => x.LookupType == (int)EnumsNeeded.EnumTypes.AdditionalDocumentTypes && x.LookupId == SectionId).LookupDesc;
return _section;
}
All files that come from DocuSign are going to be .PDF files.
Your documents will be saved as the name they were uploaded as (often contain the extension). So if you're writing the file with the name that it is stored in DocuSign by DocumentPDF->Name. I would do a .Replace and replace the extension with .pdf.

Problems with downloading pdf file from web api service

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?

Google Drive api uploads file name as "Untitled"

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...

Resources