Multipart/related upload using BackgroundUploader in Windows 8.1 - windows-runtime

I want to upload a file using Multipart/related Content-Type via BackgroundUploader in windows 8.1
My code is as follows
BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Content-Type", "multipart/related; boundary=foo_bar_baz");
uploader.Method = "POST";
// Create upload content
List<BackgroundTransferContentPart> parts = new List<BackgroundTransferContentPart>();
// File metadata
var part = new BackgroundTransferContentPart();
part.SetHeader("Content-Type", "text/plain");
part.SetText(file.DisplayName);
parts.Add(part);
// File
// Here file is of type StorageFile
part = new BackgroundTransferContentPart();
part.SetHeader("Content-Type", file.ContentType);
part.SetFile(file);
parts.Add(part);
UploadOperation upload = await uploader.CreateUploadAsync(new Uri("upload_url",UriKind.Absolute), parts);
await upload.StartAsync().AsTask(cts.token); // cts is CancellationTokenSource
However, when I run this code I get an Exception saying
WinRT information: 'boundary': If the 'Content-Type' header is set,
the boundary cannot be empty and must match the boundary set in the
'Content-Type' header.
What is wrong/missing in my code?

If you use the CreateUploadAsync with four parameters then the following might be helpful:
var uploader = new BackgroundUploader();
uploader.SetRequestHeader("Content-Type", "multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY-3770FB3C-534D-4E6B-9BE0-392FDA960F7B");
var upload = await uploader.CreateUploadAsync(uri, parts, "form-data", "0xKhTmLbOuNdArY-3770FB3C-534D-4E6B-9BE0-392FDA960F7B");
await upload.StartAsync();
Set the boundary in the "SetRequestHeader" without "" (quotes).
Set the same boundary later as the last parameter of CreateUploadAsync.

If you are passing a list of content parts, you don't need to set the Conent-Type header. It's set automatically.
However if you insist in doing so, try:
uploader.SetRequestHeader(
"Content-Type",
"multipart/form-data; boundary=\"foo_bar_baz\"");
UPDATE:
Try using the CreateUploadAsync overload that takes four parameters, where the fourth parameter is the boundary. See here: http://msdn.microsoft.com/en-us/library/ie/hh923975

Related

how to use xhr.overrideMimeType in Chrome / IE Edge?

I have an issue with sending a file (part of a request in form data format).
The issue seems coming from the fact that only in Chrome for Linux the file (which is CVS file, with .csv extension and basically just text) is sent with mimetype (Content-type in request body) Content-Type: application/octet-stream
So, I am trying to override the mimetype to match the same sent by Chrome on Linux which is text/csv.
However the mimetype is apparently not overriden and still send as octet-stream.
My code:
let xhr = new XMLHttpRequest();
let form = new FormData();
form.append('file', file, file.name); // the file is loaded correctly
form.append('payload', JSON.stringify(data)); // data is just a JSON object
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
// we arrive here both on Debian and Windows 10
}
}
xhr.upload.onerror = function() { .... } // no error
xhr.open('POST', 'http://<my_url>', true);
console.log(file.type);
xhr.overrideMimeType("text/csv");
xhr.send(form);
A couple of notes:
console.log(file.type) actually prints "text-csv" but only in Chrome for Linux (Debian specifically). in the other cases (any other browser or platform) nothing is printed
given the previous point, it seems clear to me for some reason any other browser / platform can't recognize the file type, so the file is sent as octet-stream (general binary file)
xhr.overrideMimeType changes the MIME-type of the response, not the request.
I you want to change the MIME-type of the file, just create a new Blob with an explicit file type:
var blob = new Blob([blob], {type: 'text/csv'});
form.append('file', blob, file.name);
The above changes the MIME-type of the file in the uploaded form to "text/csv", as desired.
PS. If you literally want to change the MIME-type of the whole request (instead of just the file), use xhr.setRequestHeader('Content-Type', 'custom MIME type here');. (This only makes sense if you are sending a non-standard or custom data in the xhr.send method).

WinRT: How to read images from the pictures library via an URI?

Trying to read an image that is stored in the pictures library via an URI the image is never displayed (in an Image control). Reading the same image via a stream works (assuming the app hat the Picture Library capability declared of course). Reading images from the application's data folder via an URI works.
Does someone know what could be wrong?
Here is how I (unsucessfully) try to read an image via an URI:
var imageFile = (await KnownFolders.PicturesLibrary.GetFilesAsync()).FirstOrDefault();
string imagePath = imageFile.Path;
Uri uriSource = new Uri(imagePath);
var bitmap = new BitmapImage(uriSource);
this.Image.Source = bitmap;
Here is how I sucessfully read the same image via a stream:
var imageFile = (await KnownFolders.PicturesLibrary.GetFilesAsync()).FirstOrDefault();
BitmapImage bitmap;
using (var stream = await imageFile.OpenReadAsync())
{
bitmap = new BitmapImage();
await bitmap.SetSourceAsync(stream);
}
this.Image.Source = bitmap;
I need to read the image via URI because this is the fastest way to read images and is async by nature, working perfectly with data binding.
There is no URI for the pictures library. You'll need to get the StorageFile and stream it in.
The file URI you use doesn't work because the app doesn't have direct access to the PicturesLibrary and so cannot reference items there by path. The StorageFile object provides brokered access to locations that the app doesn't natively have permissions to.

MVC 5 Content Disposition errors in Chrome and Firefox

I would like to display the user manual of the system as pdf in the browser.
The following code works fine in IE9 but not
Chrome - Error duplicate errors received from server
Firefox - Corrupted content error
The MVC 5 code ( I think is adding duplicate headers which IE can handle)
Just wondering is there any way this will work with all browsers?
public FileResult UserManual()
{
var FileName = "user-manual.pdf";
var cd = new ContentDisposition
{
Inline = true,
FileName = FileName
};
Response.AddHeader("Content-Disposition", cd.ToString());
string path = AppDomain.CurrentDomain.BaseDirectory + "App_Data/";
return File(path + FileName, MediaTypeNames.Application.Pdf, FileName);
}
I know this is old but I got into the same issue today.
If you add a "Content-Disposition" header then do not return File with the "FileName" argument added
Check this:
if (myFile.IsInlineContent()) // Evaluate the content type to check if the file can be shown in the browser
{
Response.AppendHeader("content-disposition", $"inline; myFile.Filename}");
return File(myFile.Path, myFile.Type); // return without filename argument
}
// if not, treat it as a regular download
return File(myFile.Path, myFile.Type, myFile.Filename); // return with filename argument
Hope this helps...
In order to show the file in the browser, do not provide the file name as the third parameter to the File method in your return statement. This forces a content-disposition of attachment behind the scenes. As such, your code should result in an invalid response with an ERR_RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION error.

Flickr API returning unavailable image Windows Phone

Hi I'm new to Windows Phone and the flickr API's.
I've been trying to get some images and display them on the panorama view with this code:
var baseUrl = string.Format(flickString, flickrAPIKey);
string flickrResult = await client.GetStringAsync(baseUrl);
FlickrData flickrApiData = JsonConvert.DeserializeObject<FlickrData>(flickrResult);
if(flickrApiData.stat == "ok")
{
foreach (Photo data in flickrApiData.photos.photo)
{
// To retrieve one photo
// http://farm{farmid}.staticflickr.com/{server-id}/{id}_{secret}{size}.jpeg
//string photoUrl = "http://farm{0}.staticflickr.com/{1}/{2}_{3}_o.jpeg";
//string photoUrl = "http://farm{0}.staticflickr.com/{1}/{2}_{3}_b.jpeg";
string photoUrl = "http://farm{0}.staticflickr.com/{0}/{0}_{0}_n.jpeg";
string baseFlickrUrl = string.Format(photoUrl,
data.farm,
data.server,
data.id,
data.secret);
flickr1Image.Source = new BitmapImage(new Uri(baseFlickrUrl));
break;
}
}
I've tried trying different farms & servers etc but every time it still returns "This image is unavailable at this time". I dont know what I'm doing wrong here, appreciate some help.
Thanks
After Running your link, it turns out that the image extension should use jpg instead of jpeg
But I would strongly recommend you to use the extra field to get the respective url directly by using the extra attribute in the API
extras (Optional)
A comma-delimited list of extra information to fetch for each returned record.
you can use either of those: url_sq, url_t, url_s, url_q, url_m, url_n, url_z, url_c, url_l, url_o

How to set name of file downloaded from browser?

I'm writing a web application that, among other things, allows users to upload files to my server. In order to prevent name clashes and to organize the files, I rename them once they are put on my server. By keeping track of the original file name I can communicate with the file's owner without them ever knowing I changed the file name on the back end. That is, until they go do download the file. In that case they're prompted to download a file with a unfamiliar name.
My question is, is there any way to specify the name of a file to be downloaded using just HTML? So a user uploads a file named 'abc.txt' and I rename it to 'xyz.txt', but when they download it I want the browser to save the file as 'abc.txt' by default. If this isn't possible with just HTML, is there any way to do it?
When they click a button to download the file, you can add the HTML5 attribute download where you can set the default filename.
That's what I did, when I created a xlsx file and the browser want to save it as zip file.
Download
Download Export
Can't find a way in HTML. I think you'll need a server-side script which will output a content-disposition header. In php this is done like this:
header('Content-Disposition: attachment; filename="downloaded.pdf"');
if you wish to provide a default filename, but not automatic download, this seems to work.
header('Content-Disposition: inline; filename="filetodownload.jpg"');
In fact, it is the server that is directly serving your files, so you have no way to interact with it from HTML, as HTML is not involved at all.
just need to use HTML5 a tag download attribute
codepen live demo
https://codepen.io/xgqfrms/full/GyEGzG/
my screen shortcut.
update answer
whether a file is downloadable depends on the server's response config, such as Content-Type, Content-Disposition;
download file's extensions are optional, depending on the server's config, too.
'Content-Type': 'application/octet-stream',
// it means unknown binary file,
// browsers usually don't execute it, or even ask if it should be executed.
'Content-Disposition': `attachment; filename=server_filename.filetype`,
// if the header specifies a filename,
// it takes priority over a filename specified in the download attribute.
download blob url file
function generatorBlobVideo(url, type, dom, link) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'arraybuffer';
xhr.onload = function(res) {
// console.log('res =', res);
var blob = new Blob(
[xhr.response],
{'type' : type},
);
// create blob url
var urlBlob = URL.createObjectURL(blob);
dom.src = urlBlob;
// download file using `a` tag
link.href = urlBlob;
};
xhr.send();
}
(function() {
var type = 'image/png';
var url = 'https://cdn.xgqfrms.xyz/logo/icon.png';
var dom = document.querySelector('#img');
var link = document.querySelector('#img-link');
generatorBlobVideo(url, type, dom, link);
})();
https://cdn.xgqfrms.xyz/HTML5/Blob/index.html
refs
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#download
https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition
https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types#important_mime_types_for_web_developers
Sometimes #Mephiztopheles answer won't work on blob storages and some browsers.
For this you need to use a custom function to convert the file to blob and download it
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
}
Same code as #Hillkim Henry but with a.remove() improvement
This forces the document to remove the a tag from the body and avoid multiple elements
const coverntFiletoBlobAndDownload = async (file, name) => {
const blob = await fetch(file).then(r => r.blob())
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.style.display = 'none'
a.href = url
a.download = name // add custom extension here
document.body.appendChild(a)
a.click()
window.URL.revokeObjectURL(url)
// Remove "a" tag from the body
a.remove()
}
Well, #Palantir's answer is, for me, the most correct way!
If you plan to use that with multiple files, then i suggest you to use (or make one) PHP Download Manager.
BUT, if you want to make that to one or two files, I will suggest you the mod_rewrite option:
You have to create or edit your .htaccess file on htdocs folder and add this:
RewriteEngine on
RewriteRule ^abc\.txt$ xyz.txt
With this code, users will download xyz.txt data with the name abc.txt
NOTE: Verify if you have already the "RewriteEngine on " on your file, if yes, add only the second for each file you wish to redirect.
Good Luck ;)
(Sorry for my english)