this example code in netframework 4.6
byte[] myByte = etc;
WebClient webClient = new WebClient();
webClient.Headers.Clear();
webClient.Headers.Add("Content-Type", "application/json");
webClient.Headers.Add("Authorization", "Bearer " + ChannelAccessToken);
var a1 = webClient.DownloadData("https://api.myweb.com/1");
var b1 = webClient.UploadData("https://api.myweb.com/2", myByte );
In net framework i can use this code to upload byte array to link web its my want to upload/download now i need to change to write net core how can i write this code in net core?
Related
I'm working on a ASP.NET MVC page to let users upload a Pdf document once they have digitally signed it.
But for some reason the signature is destroyed when uploading the document even when it's graphic representation is properly displayed.
Here is the code I use to upload the file:
$(document).on('click', 'input[value=Upload]', function (e, argument) {
var formdata = new FormData();
for (i = 0; i < document.getElementById('FileBox').files.length; i++) {
formdata.append(document.getElementById('FileBox').files[i].name, document.getElementById('FileBox').files[i]);
}
var url = '#Url.Action("Upload", "Test")'
var xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = $.parseJSON(xhr.response);
alert(response.result);
}
}
});
I'm retrieving the uploaded files in the controller as follows:
Public Function PostedFiles() As List(Of Byte())
Dim retval As New List(Of Byte())
Dim oRequest As HttpRequest = Web.HttpContext.Current.Request
For Each sFileKey As String In oRequest.Files
Dim oFile As HttpPostedFile = oRequest.Files(sFileKey)
If oFile.ContentLength > 0 Then
Dim iLength As Integer = oFile.ContentLength
Dim oBytes(iLength) As Byte
Dim oStream As System.IO.Stream = oFile.InputStream()
oStream.Read(oBytes, 0, iLength)
retval.Add(oBytes)
End If
Next
Return retval
End Function
After persisting the byte arrays in a SQL server database, when I take them back from the database there is no longer any signature, just the graphic representation of it.
Thanks Mkl for your comment, I realize I was getting no signature since the document was displayed in the browser. Opening the persisted file in Acrobat Reader successfully shows the signature.
I have created a web api which connects users to dropbox via OAuth. I am using an API to interact with Dropbox, which works locally as I would like, however when I deploy the API to my Azure server, I am unable to download. I had anticipated this would happen, as my API is currently hard codded to a path on my machine.
Here is the method I am using:
NOTE: I call this method through an ActionResult, as part of the MVC portion of my project
public FileSystemInfo DownloadFile(string root, string path)
{
var uri = new Uri(new Uri(DropboxRestApi.ApiContentServer),
String.Format("files?root={0}&path={1}",
root, UpperCaseUrlEncode(path)));
var oauth = new OAuth();
var requestUri = oauth.SignRequest(uri, _consumerKey, _consumerSecret, _accessToken);
var request = (HttpWebRequest) WebRequest.Create(requestUri);
request.Method = WebRequestMethods.Http.Get;
var response = request.GetResponse();
var metadata = response.Headers["x-dropbox-metadata"];
var file = ParseJson<FileSystemInfo>(metadata);
using (Stream responseStream = response.GetResponseStream())
using (MemoryStream memoryStream = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
do
{
bytesRead = responseStream.Read(buffer, 0, buffer.Length);
memoryStream.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
file.Data = memoryStream.ToArray();
}
return file;
}
This is where I call the method in my action result.
var file = api.DownloadFile("dropbox", "Public/downloadThis.jpg");
path = file.Path;
file.Save(#"....\Desktop\DemoTest\Downloads\downloadThis.jpg"); --- this is the problem & *Save* is a stream writer
Is there a procedure to follow when downloading files from a server on a browser?
public ActionResult download(Models.downloadModel dowld, Models.LoggerView log)
{
string TC_ID = Request.QueryString["id"].ToString();
string filename = TC_ID+"_LoggerData" + ".zip";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
Response.TransmitFile(Server.MapPath("~/files/" + filename));
Response.End();
}
I'm struggling with a easy problem. I want to download an image from web using this code:
WebRequest requestPic = WebRequest.Create(#"http://something.com/" + id + ".jpg");
WebResponse responsePic = await requestPic.GetResponseAsync();
Now I wanted to write the WebResponse's stream in a StorageFile (eg. create a file id.jpg in the app's storage), but I haven't found any way to achieve that. I searched the web for it, but no success - all ways incompatible Stream types and so on.
Could you please help?
I have found the following solution, which works and is not too complicated.
public async static Task<StorageFile> SaveAsync(
Uri fileUri,
StorageFolder folder,
string fileName)
{
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
var downloader = new BackgroundDownloader();
var download = downloader.CreateDownload(
fileUri,
file);
var res = await download.StartAsync();
return file;
}
You will need to read the response stream into a buffer then write the data to a StorageFile. THe following code shows an example:
var fStream = responsePic.GetResponseStream();
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync("testfile.txt");
using (var ostream = await file.OpenStreamForWriteAsync())
{
int count = 0;
do
{
var buffer = new byte[1024];
count = fStream.Read(buffer, 0, 1024);
await ostream.WriteAsync(buffer, 0, count);
}
while (fStream.CanRead && count > 0);
}
That can be done using the C++ REST SDK in Windows Store Apps. It's explained by HTTP Client Tutorial.
For public link it works fine, but in my case I need upload a image file from local disk. I converted the image into base64 format, and write the html file into local disk as well, that html file can be opened in browser with image showing, but the document in google doc just an empty file, even I drag that html file into google docs the image still not there. My code is below:
DocsService client = new DocsService("testappv3");
client.setUserCredentials("username", "password");
File file = new File("c:/test.bmp");
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
int read;
byte[] buff = new byte[1024];
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
out.flush();
String base64 = Base64.encode(out.toByteArray());
String mimeType = DocumentListEntry.MediaType.fromFileName(file.getName()).getMimeType();
String html = "<html><body><img src=\"data:" + mimeType + ";base64," + base64 + "\"/></body></html>";
URL destFolderUrl = new URL("https://docs.google.com/feeds/default/private/full/<FOLDER_ID>/contents");
DocumentEntry newDocument = new DocumentEntry();
newDocument.setTitle(new PlainTextConstruct("test"));
newDocument.setMediaSource(new MediaByteArraySource(html.getBytes(), "text/html"));
newDocument = client.insert(destFolderUrl, newDocument);
Look my experience level is only a few years so I could well be wrong but .... My understanding is that you can no longer use
client.insert(destFolderUrl, newDocument);// but now must use ResumableGDataFileUploader
new ResumableGDataFileUploader.Builder(client, new URL(uploadLink), mediaFile, null )
hopefully someone with more knowledge will confirm or deny
I have a byte array of an image on the server.
Using MVC as a pseudo-REST web service interface.
I'm in need of sending this image back through the HTTP request to the MVC client to render.
My first attempt was using UFT8Encoding to encode it to a string, send that cross then decode it using UTF8Encoding on the client.
However, when I do this, the result on the client is null. I assume due to the format of the string that I'm trying to send back.
This is what I'm doing now to no avail:
byte[] image = GetBarcodeImage(barcode);
if (image != null)
{
UTF8Encoding enc = new UTF8Encoding();
result = enc.GetString(image);
}
This is on the client side:
UTF8Encoding encoding= new UTF8Encoding();
byte[] image = encoding.GetBytes(result);
string imageBase64 = Convert.ToBase64String(image);
string imgsrc = string.Format("data:image/gif;base64,{0}", imageBase64);
Is there any reason you don't return it as an image from your controller?
var image = GetByteArrayImage();
var stream = new MemoryStream(image);
Response.Cache.SetCacheability(HttpCacheability.Public);
Response.Expires = 14400;
return File(stream, "image/jpg");
Thin in your client you can just use WebRequest to download the file like any other file and not have to do any other magic.