I have a requirement to upload files to sharepoint using sharepoint webservices.
Are there any sharepoint services which consumes the file content as base64 data inside soap request?
This resource will help you to understand this.
Here's the relevant content from the article in case the link is broken for future readers:
Let’s Upload a Document
To upload a document we need to add another service reference to
http://server/sites/personal/_vti_bin/copy.asmx. This is the Copy
service.
Here is the code to upload a document to the document library:
CopySoapClient client = new CopySoapClient();
if (client.ClientCredentials != null)
{
client.ClientCredentials.Windows.AllowedImpersonationLevel = TokenImpersonationLevel.Impersonation;
}
try
{
client.Open();
string url = "http://server/sites/personal/My Documents Library/Folder One/Folder Two/";
string fileName = "test.txt";
string[] destinationUrl = { url + fileName };
byte[] content = new byte[] { 1, 2, 3, 4 };
// Description Information Field
FieldInformation descInfo = new FieldInformation
{
DisplayName = "Description",
Type = FieldType.Text,
Value = "Test file for upload"
};
FieldInformation[] fileInfoArray = { descInfo };
CopyResult[] arrayOfResults;
uint result = client.CopyIntoItems(fileName, destinationUrl, fileInfoArray, content, out arrayOfResults);
Trace.WriteLine("Upload Result: " + result);
// Check for Errors
foreach (CopyResult copyResult in arrayOfResults)
{
string msg = "====================================" +
"SharePoint Error:" +
"\nUrl: " + copyResult.DestinationUrl +
"\nError Code: " + copyResult.ErrorCode +
"\nMessage: " + copyResult.ErrorMessage +
"====================================";
Trace.WriteLine(msg);
_logFactory.ErrorMsg(msg);
}
}
finally
{
if (client.State == CommunicationState.Faulted)
{
client.Abort();
}
if (client.State != CommunicationState.Closed)
{
client.Close();
}
}
You can use Spservises to achieve the desired functionality. Please see the code below:
function UploadFile(listName,itemId,files){
var filereader = {},
file = {};
var fileLength = files.length;
//loop over each file selected
for(var i = 0; i < files.length; i++)
{
file = files[i];
filereader = new FileReader();
filereader.filename = file.name;
filereader.onload = function() {
var data = this.result,
n=data.indexOf(";base64,") + 8;
//removing the first part of the dataurl give us the base64 bytes we need to feed to sharepoint
data= data.substring(n);
$().SPServices({
operation: "AddAttachment",
listName: listName,
asynch: true,
listItemID:itemId,
fileName: this.filename,
attachment: data,
completefunc: testFunction(i,fileLength)
});
};
filereader.onabort = function() {
alert("The upload was aborted.");
};
filereader.onerror = function() {
alert("An error occured while reading the file.");
};
//fire the onload function giving it the dataurl
filereader.readAsDataURL(file);
}
Here files is the files returned by using a html file control to upload.
I was looking for a simple soap request which can do the job, and with the help of comments from #ElvisLikeBear I was able to make use of the CopyIntoItems web service in http://server/sites/personal/_vti_bin/copy.asmx.
<SOAP:Envelope xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP:Body>
<CopyIntoItems xmlns="http://schemas.microsoft.com/sharepoint/soap/">
<SourceUrl>fileName.ext</SourceUrl>
<DestinationUrls>
<string>{your share point location to where the file has to be uploaded.}http://mySharepoint/mysharepointsite/fileName.ext</string>
</DestinationUrls>
<Fields>
<!--FieldInformation Type="Note" DisplayName="CustomerMeta_0" InternalName="" Id="12345678-4564-9875-1236-326598745623" Value="xxx" /-->
</Fields>
<Stream>Base 64 encoded content </Stream>
</CopyIntoItems>
</SOAP:Body>
</SOAP:Envelope>
Related
So I am capturing a photo and opening a stream using Xamarin.Essentials 1.7 MediaPicker built into Essentials.
When I call the ReadInStreamAsync(stream) method in Computer Vision Client, I get an error and my Xamarin.Forms app breaks inside the method: 'Invalid URI: The format of the URI could not be determined.'
This is the stream.Name value - '/data/user/0/com.companyname.xamphotoappdemo2/cache/2203693cc04e0be7f4f024d5f9499e13/198fd32db9cc4be38a493325974fa138/d964251252fc4963aca94339d73a8007.jpg'
This is my code:
var file = await MediaPicker.CapturePhotoAsync(new MediaPickerOptions
{ Title = "Please take a photo" });
if(file != null)
{
var stream = await file.OpenReadAsync();
chosenImage.Source = ImageSource.FromStream(() => stream);
// 2. Add OCR logic.
var client = Authenticate(ApiSettings.subscriptionKey, ApiSettings.endpoint);
var text = await client.ReadInStreamAsync(stream);
//after the request, get the operation location
string operationLocation = text.OperationLocation;
//we only need the operation ID, not the whole URL
const int numberOfCharsInOperationId = 36;
string operationId = operationLocation.Substring(operationLocation.Length - numberOfCharsInOperationId);
//Get the ocr read results
ReadOperationResult results;
do
{
results = await client.GetReadResultAsync(Guid.Parse(operationId));
}
while ((results.Status == OperationStatusCodes.Running || results.Status == OperationStatusCodes.NotStarted));
var readResults = results.AnalyzeResult.ReadResults;
var expirationDates = from page in readResults
from line in page.Lines
where line.Text.Contains("EXPIRES") && line.Words.Count == 4
select line.Words[3].Text;
expirationDate.Text = expirationDates.ToString();
photoPath.Text = file.FullPath;
The image is displaying as expected in the XAML Image control and that is reading the image source from the stream, so is this a bug in the ReadInStreamAsync method?
I have the response json from the backend (spring boot):
private byte[] archivoExcel;
private String extension;
private String mime;
What I need in angular is to get this byte [] and export it to excel, for this my answer json in angular is:
export class RespuestaExportar {
archivoExcel: ArrayBuffer;
extension: string;
mime: string;
}
and in my component.ts file I have:
this.reversionesService.getReversionesExportarSeguimiento(this.solicitud).subscribe(res => { this.respuestaExportar=res; let file = new Blob([this.respuestaExportar.archivoExcel], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
var fileURL = URL.createObjectURL(file); window.open(fileURL); }
When I run the 'export' button, it consumes correctly, and it downloads the excel, but this file is damaged. Do I need one more step to solve it? or there is another alternative, since I need to get this byte [] from the backEnd.
I think you can guide yourself from this service that I perform for my backend (SpringBoot) I send a responseObject as json
ObjectResponse response = new ObjectResponse();
ByteArrayInputStream in = getExcel();
byte[] array = new byte[in.available()];
in.read(array);
httpStatus = HttpStatus.OK;
response.setResultado(array);
return new ResponseEntity<>(response, httpStatus);
and I get a Json response with the structure that sent the data is that when serializing it, the response.getResult arrives in base64, that is, already transformed to the client that receives it.
So in my frontend (Angular) I proceed to transform it into a Blob and be able to work the file.
this.subcriber = this.reporteService.generarExcel (). subscribe ((b64Data: any) => {
const byteCharacters = atob (b64Data.result);
const byteNumbers = new Array (byteCharacters.length);
for (let i = 0; i <byteCharacters.length; i ++) {
byteNumbers [i] = byteCharacters.charCodeAt (i);
}
const byteArray = new Uint8Array (byteNumbers);
let blob = new Blob ([byteArray], {type: 'application / vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
const url = window.URL.createObjectURL (blob);
const anchor = document.createElement ('a');
anchor.download = `file.xlsx`;
anchor.href = url;
anchor.click ();
messageService = {
state: false,
messages: null
};
}, (err) => {
this.subcriber.unsubscribe ();
})
I hope it helps you
I'm developing a web application with spring boot, spring mvc.
I have a controller method that returned an excel file as the following:
in = new FileInputStream(comparsionreport);
out = response.getOutputStream();
response.setHeader("Content-disposition", "attachment; filename=" + comparsionreport.getName());
response.setContentType("application/vnd.ms-excel");
response.addHeader("filename", comparsionreport.getName());
byte[] buffer = new byte[BUFFER_SIZE]; // use bigger if you want
int length = 0;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.close();
In view (javascript), an AJAX call is done like the following:
$.ajax({
url : $('#compareFrm').attr('action'),
type : 'post',
responseType: "arraybuffer",
data : $('#compareFrm').serialize(),
success : function(data, status, xhr) {
// download response file
var jsonData = JSON.stringify(data);
var blob = new Blob(
[ jsonData ],
{
type: "application/vnd.ms-excel"
});
saveAs(blob, xhr.getResponseHeader('filename'));
},
error : function(data) {
}
});
An excel file with the good name is downloaded but when open it, it says that file cannot be open because of wrong extension or format (corrupted file so...)
Anyone have any idea? it's a blocking issue for me :(
Thanks
After I save my current XPages, in the event postNewDocument of datasources..I would to copy on the fly in the backend Domino Document without saving of disk the attachment from another document andI have found this solution:
var attachments:java.util.Vector = session.evaluate("#AttachmentNames", docReply);
for (var i = 0; i < attachments.size(); i++) {
embeddedObj = docReply.getAttachment(attachments.get(i).toString());
if (embeddedObj != null) {
bufferInStream = new java.io.BufferedInputStream(embeddedObj.getInputStream());
}
}
How how can I add every attachment stream into a RichTextItem of my current Domino Document?
Tnx
update 29 january 14: Tnx to #Sven I have insert this code into my PostSavedocument event..
But now I have another problem...seem that damage the MIME my "Body" that is the rt mime.
If I open with my Notes Client the document with this RT mime I see only the new attachments and not the original HTML content of CKEDITOR (If I comment the follow code...work correct)....Now I have the problem to re-edit exist MIME filed
session.setConvertMime(false);
var doc:NotesDocument=document1.getDocument(true);
var mimeRoot:NotesMIMEEntity=doc.getMIMEEntity("Body");
var docAttach:NotesDocument=database.getDocumentByUNID('XXXXXXXUNID'); //doc where are the attachmetns files MIME or RICHTEXT
var XSPReply=wrapDocument(docAttach); //function in Xsnippets from Opentntf.org
var listattachs=XSPReply.getAttachmentList("Body");
for (var i=0; i<listattachs.length; i++) {
var is=null;
var att = listattachs[i];
var persistentName = att.getPersistentName()==null?att.getName():att.getPersistentName();
var cid = att.getCID();
var eo:NotesEmbeddedObject = docAttach.getAttachment(persistentName);
if (null != eo) {
var child:NotesMIMEEntity=mimeRoot.createChildEntity(); //create child of original mail
var emailHeader:NotesMIMEHeader = child.createHeader("Content-Disposition");
emailHeader.setHeaderVal("attachment; filename=\"" + persistentName+ "\"");
emailHeader = child.createHeader("Content-ID");
emailHeader.setHeaderVal("<" + cid + ">");
var is = new java.io.BufferedInputStream(eo.getInputStream());
var stream:NotesStream = session.createStream();
stream.setContents(is);
child.setContentFromBytes(stream, att.getType(),NotesMIMEEntity.ENC_IDENTITY_BINARY);
}
}
doc.closeMIMEEntities(true,"Body")
doc.save()
session.setConvertMime(true);
You can try to add the attachments as MIME Entities. Have a look here for an example: Link
I use the following method to upload a document into sharepoint document library.
However, upon executing the query - get the following error:
Message = "The remote server returned an error: (400) Bad Request."
the files are failing over 1mb, so i tested it via the sharepoint UI and the same file uploaded successfully.
any thoughts on what's the issue is? is it possible to stream the file over rather than 1 large file chunk? the file in question is only 3mb in size..
private ListItem UploadDocumentToSharePoint(RequestedDocumentFileInfo requestedDoc, ClientContext clientContext)
{
try
{
var uploadLocation = string.Format("{0}{1}/{2}", SiteUrl, Helpers.ListNames.RequestedDocuments,
Path.GetFileName(requestedDoc.DocumentWithFilePath));
//Get Document List
var documentslist = clientContext.Web.Lists.GetByTitle(Helpers.ListNames.RequestedDocuments);
var fileCreationInformation = new FileCreationInformation
{
Content = requestedDoc.ByteArray,
Overwrite = true,
Url = uploadLocation //Upload URL,
};
var uploadFile = documentslist.RootFolder.Files.Add(fileCreationInformation);
clientContext.Load(uploadFile);
clientContext.ExecuteQuery();
var item = uploadFile.ListItemAllFields;
item["Title"] = requestedDoc.FileNameParts.FileSubject;
item["FileLeafRef"] = requestedDoc.SharepointFileName;
item.Update();
}
catch (Exception exception)
{
throw new ApplicationException(exception.Message);
}
return GetDocument(requestedDoc.SharepointFileName + "." + requestedDoc.FileNameParts.Extention, clientContext);
}
EDIT: i did find the following ms page regarding my issue (which seems identical to the issue they have raised) http://support.microsoft.com/kb/2529243 but appears to not provide a solution.
ok found the solution here:
http://blogs.msdn.com/b/sridhara/archive/2010/03/12/uploading-files-using-client-object-model-in-sharepoint-2010.aspx
i'll need to store the document on the server hosting the file then using the filestream upload process i've done in my code below:
private ListItem UploadDocumentToSharePoint(RequestedDocumentFileInfo requestedDoc, ClientContext clientContext)
{
try
{
using(var fs = new FileStream(string.Format(#"C:\[myfilepath]\{0}", Path.GetFileName(requestedDoc.DocumentWithFilePath)), FileMode.Open))
{
File.SaveBinaryDirect(clientContext, string.Format("/{0}/{1}", Helpers.ListNames.RequestedDocuments, requestedDoc.FileName), fs, true);
}
}
catch (Exception exception)
{
throw new ApplicationException(exception.Message);
}
return GetDocument(requestedDoc.SharepointFileName + "." + requestedDoc.FileNameParts.Extention, clientContext);
}