I have a File.aspx form where I display all the files.
When I upload a file I am using a upload.aspx file to run c# code to upload the file.
The thing is that at the end , I want to refresh the page automatically to display the new file upload but apparently it's not redirecting even if all the parameters are good.
This is the code I use
HttpContext postedContext = HttpContext.Current;
string param = Request.UrlReferrer.Query;
string param2 = Request.UrlReferrer.Query;
var url = HttpUtility.ParseQueryString(param).Get("projectName");
var url2 = HttpUtility.ParseQueryString(param2).Get("projectId");
HttpPostedFile file = postedContext.Request.Files[0];
string name = file.FileName;
byte[] binaryWriteArray = new
byte[file.InputStream.Length];
file.InputStream.Read(binaryWriteArray, 0,
(int)file.InputStream.Length);
//FileStream objfilestream = new FileStream(Server.MapPath("~\\" + "\\Files\\" + url + "\\" + name), FileMode.Create, FileAccess.ReadWrite);
FileStream objfilestream = new FileStream(("C:\\inetpub\\wwwroot\\Clientportal\\Files\\" + url + "\\" + name), FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length);
objfilestream.Close();
string[][] JaggedArray = new string[1][];
JaggedArray[0] = new string[] { "File was uploaded successfully" };
JavaScriptSerializer js = new JavaScriptSerializer();
string strJSON = js.Serialize(JaggedArray);
Response.Write(strJSON);
Response.Redirect(string.Format("Files.aspx?projectId={0}&projectName={1}", url2, url));
Any ideas ? I'm a bit stuck because I use this response.redirect everywhere and it works only when the code is in the same code file...
Maybe it's because of the fact that I try to redirect from another code file ?
I would attempt to do reload on client side by using javascript:
window.location.reload()
if the JSON you get as a response contains message "File was uploaded successfully"
If you are not using ajax for submitting the file you don't need to write json. It's enough to redirect to the suitable url that contains a parameter that identifies status of file upload operation.
Related
I have build an API which gives output in zip file when more than one file is requested
Now I have to download this zip file in C# WPF app.
To access API, we have to use POST ( instead of GET ) and JSON parameters.
I am able to download one file as string with help of below code
WebClient client = new WebClient();
var vm = new { from = "A", to = "S", files= "all", type = "csv", file = "Single" };
client.Headers[HttpRequestHeader.ContentType] = "application/json";
var dataString = JsonConvert.SerializeObject(vm);
var response = client.UploadData("https://myurl.com/data", "POST", System.Text.Encoding.ASCII.GetBytes(dataString));
But not able to figure out how to download zip file and save it to disk
I am currently trying to make a post request with a file attached to the form but I found out that it is not the file I have attached but just the path to the file.
My question is how do I get this file and attach it to the form?
Here is my code so far:
string altPath = Path.Combine(Application.persistentDataPath, "nice-work.wav");
List<IMultipartFormSection> formData = new List<IMultipartFormSection>();
formData.Add(new MultipartFormFileSection("wavfile", altPath));
UnityWebRequest uwr = UnityWebRequest.Post(url, formData);
yield return uwr.SendWebRequest();
if (uwr.isNetworkError)
{
Debug.Log("Error While Sending: " + uwr.error);
}
else
{
Debug.Log("Received: " + uwr.downloadHandler.text);
}
the variable altPath is the path but not the file and this leads to failed post request.
If you look at MultipartFormFileSection the constructor you are currently using is
MultipartFormFileSection(string data, string fileName)
which is of course not what you want to do.
You rather have to actually read the according file content e.g. simply using File.ReadAllBytes
...
var multiPartSectionName = "wavfile";
var fileName = "nice-work.wav";
var altPath = Path.Combine(Application.persistentDataPath, fileName);
var data = File.ReadAllBytes(altPath);
var formData = new List<IMultipartFormSection>
{
new MultipartFormFileSection(multiPartSectionName, data, fileName)
};
...
or depending on your server side needs
...
var formData = new List<IMultipartFormSection>
{
new MultipartFormFileSection(fileName, data)
};
...
Though have in mind that ReadAllBytes is a synchronous (blocking) call and for larger files you might rather want to use some asynchronous approach.
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!
I am trying to upload files to Google Drive using ASP.NET Core 3.0, here is my code to upload the file.
GData.File fileMetadata = new GData.File()
{
Id = null,
Name = Path.GetFileName(path),
MimeType = contentType
};
using (Stream stream = new FileStream(path, FileMode.Open, FileAccess.ReadWrite))
{
FilesResource.CreateMediaUpload request = service.Files.Create(fileMetadata, stream, contentType);
request.Fields = "id";
request.Body = fileMetadata;
request.ProgressChanged += (uploadProgress) =>
{
Debug.WriteLine($"{uploadProgress.Status} {uploadProgress.BytesSent}");
};
request.ResponseReceived += (obj) =>
{
Debug.WriteLine($"File uploaded successfully {obj.Id}");
};
request.Upload();
}
Problem i am facing is, this method work fine when i run it on local IIS Server. On Remote IIS Server this method run successfully but uploaded file do not have any content in it and show 0 size
follow this link to test:
https://oauthdemo.coredata.ca/
I tested the link you provided, but the test results show that the Content-Length has a size.
After struggling of whole day finally i have sort this issue.
It was due to the temp folder. i was using FileStream to create new file in temp folder. It was a A-Sync call due to which FileStream failed to create that file.
I have an Angular application with an ASP.NET Web API.
I want to download a file stored on my server. Currently, this is the code I have:
[HttpGet]
[Route("downloadFile")]
[JwtAuthentication] //Only a connected user can download the file
public async Task<HttpResponseMessage> DownloadFile(string path)
{
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var fileStream = File.OpenRead(path);
result.Content = new StreamContent(fileStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
result.Content.Headers.ContentLength = fileStream.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileStream.Name,
Size = fileStream.Length
};
return result;
}
And in my Angular code:
// file-navigation.service.ts
downloadFile(file: FileElement) {
const data = { path: this.formatPath(true) + file.name };
return this.http.get(this.apiUrl + '/downloadFile', { params: data, responseType: 'blob' });
}
// file-navigation.component.ts
this.fileNavigationService.downloadFile(element).subscribe(result => {
this.generateDownload(element, result, false);
});
generateDownload(element: FileElement, blob: Blob, isArchive: boolean) {
const fileName = element != null ? element.name : 'Archive';
if (navigator.appVersion.toString().indexOf('.NET') > 0) {
window.navigator.msSaveBlob(blob, fileName + (isArchive ? '.zip' : ''));
} else {
const link = document.createElementNS(
'http://www.w3.org/1999/xhtml',
'a'
);
(link as any).href = URL.createObjectURL(blob);
(link as any).download = fileName + (isArchive ? '.zip' : '');
document.body.appendChild(link);
link.click();
setTimeout(function () {
document.body.removeChild(link);
link.remove();
}, 100);
}
}
With this, I successfully download a file from the server.
However, the download bar in Chrome only appears when the download is done. So if the file is too big, the user won't get any indicator that his file is currently being downloaded.
Below is a screenshot of a 16Mb file being downloaded. The server is currently sending data but the download bar doesn't appear.
Then, once the download has completed, the file appears in the download bar at the bottom of the screen.
How can I send the file to the browser so that it shows this indicator to the user?
Thank you very much.
EDIT:
As #CodeCaster pointed out, redirecting to the URL could work, however, my URL is protected so that only connected users can download the file.
On Angular side, just use anchor tag and pass the API URL in href attribute.
<a href = {this.apiUrl + '/downloadFile' + '?' + 'your params'}>Download</a>
and also on server side before streaming data, make sure you have set the following response header.
res.setHeader('content-length',data.ContentLength) (optional)
res.setHeader('content-type', mimetype);
res.setHeader('content-disposition', 'attachment; filename');