I use this code to upload pdf files to sharepoint in my WinForm application. it works. when I click it try to open in sharepoint, I got this
"The document could not be opened for editing. A Windows SharePoint Services compatible application could not be found to edit the document"
If I upload manually, click opens fine.
Here is the code:
FileStream fStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fStream);
byte[] bytes = br.ReadBytes((int)numBytes);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/pdf";
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
byte[] buffer = new byte[1024];
using (Stream stream = request.GetRequestStream())
using (MemoryStream ms = new MemoryStream(bytes))
for (int i = ms.Read(buffer, 0, buffer.Length); i > 0; i = ms.Read(buffer, 0, buffer.Length))
stream.Write(buffer, 0, i);
WebResponse response = request.GetResponse();
response.Close();
Related
I'm trying to generate an excel file / stream in my web api and return it in a HttpResponseMessage to serve it to the client in Angular 5 as a download.
The generation succeeds and an xlsx file is generated and saved on the server, but when I return it in the Content of my httpResponseMessage, my browser shows just some json instead of the whole excel file.
{"version":{"major":1,"minor":1,"build":-1,"revision":-1,"majorRevision":-1,"minorRevision":-1},"content":{"headers":[{"key":"Content-Disposition","value":["attachment; filename=636742856488421817.xlsx"]},{"key":"Content-Type","value":["application/ms-excel"]},{"key":"Content-Length","value":["22780"]}]},"statusCode":200,"reasonPhrase":"OK","headers":[],"requestMessage":null,"isSuccessStatusCode":true}
This is how I create the excel file and returns it:
var dataBytes = File.ReadAllBytes(fileName);
var dataStream = new MemoryStream(dataBytes);
HttpResponseMessage httpResponseMessage = new HttpResponseMessage(HttpStatusCode.OK);
httpResponseMessage.Content = new StreamContent(dataStream);
httpResponseMessage.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
httpResponseMessage.Content.Headers.ContentDisposition.FileName = fileName;
httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
httpResponseMessage.Content.Headers.ContentLength = dataStream.Length;
I solved this:
Here is what I did
Helper class which creates the excel package and converts it to a Stream
var fileName = DateTime.Now.Ticks + ".xlsx";
FileInfo file = new FileInfo(fileName);
FileInfo templateFile = new FileInfo(#"Templates/ReportTemplate.xlsx");
ExcelPackage package = new ExcelPackage(file, templateFile);
ExcelWorksheet worksheet = package.Workbook.Worksheets.FirstOrDefault();
... filling rows and cells goed here ...
var dataBytes = package.GetAsByteArray();
Stream dataStream = new MemoryStream(dataBytes);
dataStream.Seek(0, SeekOrigin.Begin);
return dataStream;
In the controller I return the file to the Angular client like this:
var stream = _helperClass.GenerateReport(exportDate, exportTitle);
return File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", $"Report-{DateTime.Now.ToShortDateString()}.xlsx");
In the Angular component I do this after I receive the response:
var blob = new Blob([res], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
var blobURL = window.URL.createObjectURL(blob);
var anchor = document.createElement("a");
anchor.download = `Report-${new Date().toISOString()}.xlsx`;
anchor.href = blobURL;
anchor.click();
Try this following code:
For conroller:
[Route("DownLoadExcel")]
public IActionResult DownLoadExcel()
{
var pack = new ExcelPackage();
ExcelWorksheet worksheet = pack.Workbook.Worksheets.Add("sample");
//First add the headers
worksheet.Cells[1, 1].Value = "ID";
worksheet.Cells[1, 2].Value = "Name";
//Add values
worksheet.Cells["A2"].Value = 1000;
worksheet.Cells["B2"].Value = "Jon";
return File(pack.GetAsByteArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Sample.xlsx");
}
For client side:
window.open("../.../DownLoadExcel");
I have a problem in API Management, I want to create images in item 1 item, but I still can not do it forever. I use c # language, I feel depressed
i want to create a resource in catchoom.
can you help me
byte[] buffer = null;
byte[] data = null;
byte[] data1 = null;
HttpWebRequest request = null;
int bytesRead = 0;
long length = 0;
string boundary = DateTime.Now.Ticks.ToString("x");
// string boundary = "AaB03x";
StringBuilder sb = null;
// Create the HttpWebRequest object
request = (HttpWebRequest)HttpWebRequest.Create("https://crs.catchoom.com/api/v0/image/?api_key=5aba12ba6974c04ebc95da45ba1597d27d75238f");
// Specify the ContentType
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
// Specify the Method
request.Method = "POST";
request.KeepAlive = false;
// Create the StringBuilder object
sb = new StringBuilder();
// Constrcut the POST header message
sb.AppendLine("");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: form-data; name=\"anh\"");
sb.AppendLine("");
sb.AppendLine("/api/v0/item/aee726ff67274fcb80f4c24f27861c1e/");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: file; name=\"anh\"; filename=\"anh\"");
sb.AppendLine("Content-Type: image/jpg");
sb.AppendLine("");
StringBuilder sb1 = new StringBuilder();
sb1.AppendLine("");
sb1.AppendLine("--" + boundary + "--");
// Convert the StringBuilder into a string
data = Encoding.UTF8.GetBytes(sb.ToString());
data1 = Encoding.UTF8.GetBytes(sb1.ToString());
//
using (FileStream fs = new FileStream(#"D:\17. NHATLINH\ToolKit_Catchoom\ToolKit_Catchoom\bin\Debug\aa.jpg", FileMode.Open, FileAccess.Read))
{
length = data.Length + fs.Length + data1.Length;
// đưa thông tin chiều dài của gói gửi đi vào
request.ContentLength = length;
//
using (Stream stream = request.GetRequestStream())
{
// ghi header vào gói gửi đi
stream.Write(data, 0, data.Length);
//
buffer = new Byte[checked((uint)Math.Min(4096, (int)fs.Length))];
// buffer = new Byte[fs.Length];
// Write the file contents
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
stream.Write(data1, 0, data1.Length);
//
try
{
Console.WriteLine(request.ContentType);
Console.WriteLine(sb.ToString() + sb1.ToString());
WebResponse responce = request.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
MessageBox.Show(sr.ReadToEnd());
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
}
Building a multipart-encoded request is an error-prone task ( it is normal if you feel frustrated trying ), I recommend you to use a library to handle this kind of things, no point in reinventing the wheel :)
If you are using the Microsoft .NET Framework >= 4.5, you may use the HttpClient class as this answer explains.
Hope this help you ;)
I'm having a Windows 8 app which is working pretty well and now I want to write the same app for Windows Phone 8, but I'm only getting a black image and not the right image.
This is my code for uploading the image file
if ((_fileType == ".jpg" || _fileType == ".png" || _fileType == ".jpeg") && _fileSize < 3500000)
{
byte[] myPicArray = ConvertToBytes(_bmpFile);
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(MYURI);
MultipartFormDataContent form = new MultipartFormDataContent();
HttpContent content = new ByteArrayContent(myPicArray);
form.Add(content, "media", _randomStringFileName + _fileType);
HttpResponseMessage response = await httpClient.PostAsync("upload.php", form);
}
and this is the code for converting my image to a byte array
private byte[] ConvertToBytes(BitmapImage bitmapImage)
{
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap btmMap = new WriteableBitmap
(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
// write an image into the stream
Extensions.SaveJpeg(btmMap, ms,
bitmapImage.PixelWidth, bitmapImage.PixelHeight, 0, 100);
return ms.ToArray();
}
}
Has anybody an idea why I'm only getting a black image and not the right image? The image was selected by the PhotoChooseTask.
The PhotoChooseTask already gives you the Stream, so you'll just need to use that instead (You can't use the BitMap yet because it's still busy writing it to the device and generating thumbnails, etc)
PhotoResult photoResult = e as PhotoResult;
MemoryStream memoryStream = new MemoryStream();
photoResult.ChosenPhoto.CopyTo(memoryStream);
byte[] myPicArray = memoryStream.ToArray();
I'm developing a rather simple visual WebPart for SharePoint Foundation Server 2010.
It's supposed to upload an image file to the SharePoint server and display it afterwards.
While I can successfully upload the file to a previously created document library, the file cannot be displayed (IE shows the red cross). When I upload an exact copy of the file using SharePoint frontend, it can be opened. I hope that someone can tell me what I'm missing.
Below you can find the code that successfully uploads a file to the server:
SPContext.Current.Web.AllowUnsafeUpdates = true;
string path = "";
string[] fileName = filePath.PostedFile.FileName.Split('\\');
int length = fileName.Length;
// get the name of file from path
string file = fileName[length - 1];
SPWeb web = SPContext.Current.Web;
SPFolderCollection folders = web.Folders;
SPFolder folder;
SPListCollection lists = web.Lists;
SPDocumentLibrary library;
SPList list = null;
Guid guid = Guid.Empty;
if (lists.Cast<SPList>().Any(l => string.Equals(l.Title, "SPUserAccountDetails-UserImages")))
{
list = lists["SPUserAccountDetails-UserImages"];
}
else
{
guid = lists.Add("SPUserAccountDetails-UserImages", "Enthält Mitarbeiter-Fotos", SPListTemplateType.DocumentLibrary);
list = web.Lists[guid];
}
library = (SPDocumentLibrary)list;
folder = library.RootFolder.SubFolders.Add("SPUserAccountDetails");
SPFileCollection files = folder.Files;
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
Stream stream = new MemoryStream();
stream.Read(MyData, 0, (int)fStream.Length);
fStream.Close();
bool bolFileAdd = true;
for (int i = 0; i < files.Count; i++)
{
SPFile tempFile = files[i];
if (tempFile.Name == file)
{
folder.Files.Delete(file);
bolFileAdd = true;
break;
}
}
if (bolFileAdd)
{
SPFile f = files.Add(file, MyData);
f.Item["ContentTypeId"] = "image/jpeg";
f.Item["Title"] = file;
f.Item.SystemUpdate();
SPContext.Current.Web.AllowUnsafeUpdates = false;
imgPhoto.ImageUrl = (string)f.Item[SPBuiltInFieldId.EncodedAbsUrl];
}
Never mind. My code seems to mess with the file content. I'll post the solution later.
edit:
I'm stupid and sorry :-/
I replaced this:
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
Stream stream = new MemoryStream();
stream.Read(MyData, 0, (int)fStream.Length);
fStream.Close();
with this:
Stream fStream = filePath.PostedFile.InputStream;
byte[] MyData = new byte[fStream.Length];
BinaryReader binaryReader = new BinaryReader(fStream);
MyData = binaryReader.ReadBytes((Int32)fStream.Length);
fStream.Close();
binaryReader.Close();
and suddenly it all worked ;-)
On button click event or on Link button click, I want to download document from sharepoint document library and save it to the user's local disk.
Plz help me on this,If you have any code sample then please share
The problem with outputting a direct link to the file, is that for some content types it may just open in the browser window. If that is not the desired outcome, and you want to force the save file dialog, you'll need to write an ASP/PHP page that you could pass a filename to via the querystring. This page could then read the file and set some headers on the response to indicate that the content-disposition is and attachment.
For ASP.net, if you create a simple aspx page called download.aspx, add the following code into it, then put this file on a server somewhere you can download files by calling this page like this:
http://yourserveraddress/download.aspx?path=http://yoursharepointserver/pathtodoclibrary/file.ext
protected void Page_Load(object sender, EventArgs e)
{
string path = "";
string fileName = "";
path = Request.QueryString["path"];
if (path != null && path.Length > 0)
{
int lastIndex = path.LastIndexOf("/");
fileName = path.Substring(lastIndex + 1, (path.Length - lastIndex - 1));
byte[] data;
data = GetDataFromURL(path);
Response.Clear();
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(data);
Response.Flush();
}
}
protected byte[] GetDataFromURL(string url)
{
WebRequest request = WebRequest.Create(url);
byte[] result;
byte[] buffer = new byte[4096];
//uncomment this line if you need to be authenticated to get to the files on SP
//request.Credentials = new NetworkCredential("username", "password", "domain");
using (WebResponse response = request.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
using (MemoryStream ms = new MemoryStream())
{
int count = 0;
do
{
count = responseStream.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, count);
} while (count != 0);
result = ms.ToArray();
}
}
}
return result;
}
I'd create a LinkButton and set the URL to the document's url programmatically.