I have found some answers here that give examples but none seems to work for me..
this is how my postman looks:
In the code I download the picture from a URL, save it as jpeg inside a folder and then I try to upload that image with a POST request, here is how it looks:
var fileName = image.PhotoId + ".jpeg";
await Task.WhenAll(client.DownloadFileTaskAsync(new Uri(image.ImageUrl), #"wwwroot\images\"+fileName));
var files = Directory.GetFiles(#"wwwroot\images\", "*.jpeg");
var filePath = Path.Combine(#"wwwroot\images\", fileName);
using var stream = File.OpenRead(filePath);
var file_content = new ByteArrayContent(new StreamContent(stream).ReadAsByteArrayAsync().Result);
var formData = new MultipartFormDataContent();
formData.Add(file_content, "file", fileName);
var res = await clientAsync.PostAsync(url, formData);
problem is the response that I get in the code is an error..:
{"error_code":6,"error_message":"Sorry, please try a different picture"}
this type of response is the same one I get when trying to upload a pdf instead of a jpeg on postman so I guess the file is getting corrupted in the code somewhere.
would love to get any ideas to where the problem is!
Related
I have a script that uploads a video to an API I built, and after it processes on the API side, a text file is returned to the client. The strange thing is, this only works with one type of file, a .QT file extension. Any other video type I try to send sends and empty video. I have tried .mov, .mp4, and .qt and only the .qt uploads properly. I'll post my code below. Would anyone know what cause only the one file type to work? Nothing on the API side singles out the qt file. I believe this is an issue with this script.
public async void Function() {
Debug.Log("works1");
string filePath = "IMG_0491.mov";
//string filePath = ProcessMode.theFilePath;
var client = new HttpClient();
using (var multipartFormContent = new MultipartFormDataContent()) {
//Add the file
Debug.Log("works2");
var fileStreamContent = new StreamContent(File.OpenRead(filePath));
Debug.Log("works3");
fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("video/mov");
multipartFormContent.Add(fileStreamContent, name: "file", fileName: filePath); //Originally Actual "Name`
//Send it
var response = await client.PostAsync("http://127.0.0.1:5000/", multipartFormContent); //Enter IP and Port of API when set up
Debug.Log("works4");
//Ensure it was successful.
response.EnsureSuccessStatusCode();
//Grab the animation data from the content.
var animation_data = await response.Content.ReadAsStringAsync();
Debug.Log(animation_data);
//Save to file.
//File.WriteAllTextAsync("AnimationFile.txt", animation_data);
await File.WriteAllTextAsync("AnimationFile.txt", animation_data);
Debug.Log("works5");
}
Helo, i already search on Google and here (StackOverflow) but no any solution i complete.
I Have a Excel file in my folder and i need to create a method on my controller to download this file.
And in my React Web Site i need to get this file to user computer.
I try to use ActionResult, FileStreamResult, HttpResponseMessage and other, read file from folder with File.ReadAllbytes, put the Header on response.
On the final i get this.
{ FileContents: "allcontentoffilehere....", Contenttype: "application/octet-stream", FileDownloadName: "filename.xls"}
And using this JavaScript do download:
var bytes = new Uint8Array(responseDownloadFile.data.FileContents);
var blob = new Blob([bytes], {
type: responseDownloadFile.data.ContentType
});
const link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = responseDownloadFile.data.FileDownloadName;
document.body.appendChild(link);
link.click();
But the file when download is corrupted.
Any on can help me?
Try to return HttpResponseMessage type on your API
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent([file bytes]);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/file type");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "filename.xlsx"
};
return result;
And on your Front end execute code:
window.location.href = "link to your api endpoint to download excel";
I can upload images to Slack via my SlackAPI and I can upload files and I can upload images with comments - but I can not do this with files that are no images.
I'm sure it's a problem with my message-structure - have a look: All this is done via HttpClient!
This is my working fileUpload-method:
public MultipartFormDataContent SendFileToChannel()
{
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(GetFile.ReadFile());
requestContent.Add(new StringContent(token), "token");
requestContent.Add(fileContent, "file", Path.GetFileName(GetFile.path));
return requestContent;
}
there is no 'channel' in this method because I don't want to publish it yet.
Then I set "public_url_shared": true and get the public URL(with another method).
In the response evreything seems to be okay, shared is set to true and I get a permalink_public-value which I pass on to post a message containing this file but...
Now I should be able to post a message while using the permalink_url I get from the second method. And this works with images. But it doesn't work with files.
I allways get the error response "no_file_data".
Here is my method for this:
public MultipartFormDataContent SendMessageWithFile(SlackFileResponse resp)
{
var requestContent = new MultipartFormDataContent();
requestContent.Add(new StringContent(token), "token");
requestContent.Add(new StringContent(channel), "channel");
requestContent.Add(new StringContent(text), "text");
requestContent.Add(new StringContent("[{ \"fallback\":\"Anhang\", \"text\":\"\", \"\":\"" + resp.permalink_public + "\"}]"), "attachments");
return requestContent;
}
Am I doing something wrong here? Because via the RTM-Slack one can easily just drag&drop a file in there and add a message to it. So it has to be possible via the SlackAPI ,too. Right?
Here is why this approach does not work:
Slack threats images differently from other files. Images are the only type of file that you can include in a message attachment via URL. For that we have the properties image_url (and thumb_url) for attachments.
Check out this page for a list of all available attachment properties.
If you want to post any other file in a Slack channel and be able to comment it you need to upload it via files.upload and share it immediately. That is important, because it is currently not possible via the official API to share a previously uploaded file in a channel at a later point.
To include a comment with your file upload just set the initial_comment property in your API call.
Example:
var requestContent = new MultipartFormDataContent();
var fileContent = new StreamContent(GetFile.ReadFile());
requestContent.Add(new StringContent(token), "token");
requestContent.Add(new StringContent("my_channel"), "channels");
requestContent.Add(new StringContent("Check out this amazing new file"), "initial_comment");
requestContent.Add(fileContent, "file", Path.GetFileName(GetFile.path));
I have an issue with ASP.Net HttpClient POST request.
In fact I want to index documents in Solr using SolrCell. I have used curl like this:
curl 'http://localhost:8983/solr/my_collection/update/extract?literal.id=doc1&commit=true' -F "myfile=#example/exampledocs/solr-word.pdf"
Unfortunately I was only able to send the file as Multi-part file upload (with HttpClient), this way I need to determine the mime type of the file, which I did but I still got errors for DOCX and PPTX files.
Here is my code:
var fileBytes = File.ReadAllBytes(path);
requestContent.Add(new ByteArrayContent(fileBytes), "file");
requestContent.Headers.Remove("Content-Type");
requestContent.Headers.Add("Content-Type", contentType);
var response = await client.PostAsync(defaultSolrUri, requestContent);
return response.Content;
Please help.
I found the solution! No need to pass MultiPartFormData, all you need to do is to pass the file as ByteArrayContent in PostAsyn:
string path = "path/to/file";
var fileBytes = File.ReadAllBytes(path);
var response = await client.PostAsync(defaultSolrExtractUri, new ByteArrayContent(fileBytes));
return response.Content;
I have files on a server that can be accessed from a URL formatted like this:
http:// address/Attachments.aspx?id=GUID
I have access to the GUID and need to be able to download multiple files to the same folder.
if you take that URL and throw it in a browser, you will download the file and it will have the original file name.
I want to replicate that behavior in C#. I have tried using the WebClient class's DownloadFile method, but with that you have to specify a new file name. And even worse, DownloadFile will overwrite an existing file. I know I could generate a unique name for every file, but i'd really like the original.
Is it possible to download a file preserving the original file name?
Update:
Using the fantastic answer below to use the WebReqest class I came up with the following which works perfectly:
public override void OnAttachmentSaved(string filePath)
{
var webClient = new WebClient();
//get file name
var request = WebRequest.Create(filePath);
var response = request.GetResponse();
var contentDisposition = response.Headers["Content-Disposition"];
const string contentFileNamePortion = "filename=";
var fileNameStartIndex = contentDisposition.IndexOf(contentFileNamePortion, StringComparison.InvariantCulture) + contentFileNamePortion.Length;
var originalFileNameLength = contentDisposition.Length - fileNameStartIndex;
var originalFileName = contentDisposition.Substring(fileNameStartIndex, originalFileNameLength);
//download file
webClient.UseDefaultCredentials = true;
webClient.DownloadFile(filePath, String.Format(#"C:\inetpub\Attachments Test\{0}", originalFileName));
}
Just had to do a little string manipulation to get the actual filename. I'm so excited. Thanks everyone!
As hinted in comments, the filename will be available in Content-Disposition header. Not sure about how to get its value when using WebClient, but it's fairly simple with WebRequest:
WebRequest request = WebRequest.Create("http://address/Attachments.aspx?id=GUID");
WebResponse response = request.GetResponse();
string originalFileName = response.Headers["Content-Disposition"];
Stream streamWithFileBody = response.GetResponseStream();