I am currently working on a project in which we want to store image on separate sever. I don't now how to connect both the server so that i can easily save image on remote server.
if (Request.Files.AllKeys.Any())
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
string oldFileName = file.FileName;
NewFileName = Guid.NewGuid().ToString();
string FileExtention = oldFileName.Substring(oldFileName.LastIndexOf('.') + 1);
if (FileExtention == "blob")
{
FileExtention = "jpg";
}
NewFileName = NewFileName + "." + FileExtention;
var fileSavePath = Path.Combine(Server.MapPath("~" + filePath + "Document"), file.FileName.Replace(oldFileName, NewFileName));
file.SaveAs(fileSavePath);
VisitDocument document = new VisitDocument();
document.VisitId = vid;
document.Title = oldFileName.Substring(0, oldFileName.LastIndexOf('.'));
document.RefPath = (filePath + "Document/" + NewFileName).Replace("/", #"\").Substring(1);
document.CreatedBy = tempUser.UserId;
document.CreatedOn = DateTime.Now;
document.IsDeleted = 0;
dal.VisitDocuments.Add(document);
dal.SaveChanges();
}
}
You have two options to do:
1- Use Web API application to do this task and deploy it on the server you want.
2- Open connection on the server and save the file there but you need to have account on this server and this account has the privileges to write and read.
string path = #"\\xxx.xxx.xxx.xxx\Uploads\"; // server IP
if (!System.IO.Directory.Exists(serverPath))
System.IO.Directory.CreateDirectory(path );
file.SaveAs(path + FileName);
Related
I am following these steps.
I am uploading the files of TEXT / PNG / DOCX / PPTX for the DocuSign using
c# API.
when I download that file after the signature of the document I got PDF format of that signature document except for uploaded file format.
Is there any alternate way of code or API how I got the same extension file on the download after signature done.
Envelope ID:- 3a6b752a-92f1-4751-b06a-ffb2c236f65d , 93409bdc-edcf-4e4b-8c6f-3c76c6305dcf , 5a32979b-3739-4585-a554-b725e1d65504
I am using below code in asp.net.
// get Lists the envelope documents.
public static EnvelopeDocumentsResult ListEnvelopeDocuments(string accountId, string envelopeId)
{
EnvelopesApi envelopesApi = new EnvelopesApi();
EnvelopeDocumentsResult docsList = envelopesApi.ListDocuments(accountId,
envelopeId);
return docsList;
}
// download file using envelopeId and that I get .pdf format
public static string DownloadSignedDocument(string envelopeId, string tempFileName, string companyCode, string apiUserName, string apiPassword, string integratorkey, string restApi)
{
ApiClient apiClient = new ApiClient(restApi);
Configuration.Default.ApiClient = apiClient;
// call the Login() API which sets the user's baseUrl and returns their accountId
string accountId = LoginApi(apiUserName, apiPassword, integratorkey);
// pass accountid and envelop id to get perticuler document for the download
EnvelopeDocumentsResult documentList = ListEnvelopeDocuments(accountId,
envelopeId);
string SignedPDFPath = string.Empty;
EnvelopesApi envelopesApi = new EnvelopesApi();
foreach (EnvelopeDocument document in documentList.EnvelopeDocuments)
{
MemoryStream docStream =
(MemoryStream)envelopesApi.GetDocument(accountId,
envelopeId, documentList.EnvelopeDocuments[0].DocumentId);
string documentName = document.Name != "Summary" ? document.Name :
"Summary";
SignedPDFPath =
systemConfiguration.ConfigurationManager.AppSettings["uploadFolder"] +
"/" + companyCode + "/" + "DocuSign/" + envelopeId;
if (!Directory.Exists(SignedPDFPath))
{
Directory.CreateDirectory(SignedPDFPath);
}
string[] tempFileExtention = tempFileName.Split('.');
string[] removeFileExtention = documentName.Split('.');
// need to give hardcoded ".pdf" extention because **document.Name**
//gives pdf file formate
SignedPDFPath = SignedPDFPath + "/" + removeFileExtention[0] + ".pdf"
;
// Server.MapPath("~/Uploadfiles/" + recipient.EnvelopeID + "/" +
// recipient.EnvelopeID + "_" + documentName + ".pdf");
using (FileStream fileStream = File.Create(SignedPDFPath))
{
docStream.Seek(0, SeekOrigin.Begin);
docStream.CopyTo(fileStream);
}
break;
}
return SignedPDFPath;
}
No.
All files are converted to PDF upon upload to DocuSign. If desired, you could use external tools to convert that PDF into another file format, but you would be breaking the 'tamper evident' digital seal on the document.
I am saving image file on google drive using asp.net mvc and webapi. I want full image path. What is the alternate to get full path?
My method in Webapi:
private void UploadImage(DriveService service, string imageId)
{
string FOLDER_NAME = "ProductImages";googleFile.File folder = searchFolder(service,FOLDER_NAME);if(folder == null)
folder = createFolder(service,FOLDER_NAME);
var folderId = folder.Id;
var fileMetaData = new googleFile.File();
//fileMetaData.Name = Path.GetFileName(imageId);--not getting full path
fileMetaData.Name = imageId;
fileMetaData.MimeType = "image/jpg";
fileMetaData.Description = "Upload Image";
fileMetaData.Parents = new List<string> { folderId };
FilesResource.CreateMediaUpload request;
// imageId = #"D:\Camera\IMG_20130525_220410.jpg";
using (var stream = new FileStream(imageId, FileMode.Create))-- i get wrong path in imageid.due to that i get error
{request = service.Files.Create(fileMetaData, stream, "image/jpg");
request.Fields = "id";
var upload = request.UploadAsync();
var file = request.ResponseBody;}
I am encountering a problem in getting the download prompt. In the below code first am allowing the user to upload a file to compress. Once the file is compressed the user should be provided with the compressed files. But in the below code download prompt doesn't appears neither it shows any error. Please help me by correcting my code
The view code:
function CompressFile(box) {
var file = document.getElementById('fileComp');
if (file.value == "") {
alert("Choose a file to upload");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Compress', true);
xhr.send(fd);
}
The controller code:
public ActionResult Compress(HttpPostedFileBase file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file.FileName) ?? "";
if (file.ContentLength > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_uploadPDF), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
PdfReader reader = new PdfReader(filePath);
string name = DateTime.Now.ToString("ddMM_HHmmss");
name = Server.MapPath(_fileUploadPath + name + ".pdf");
PdfStamper stamper = new PdfStamper(reader, new FileStream(name, FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = true;
stamper.SetFullCompression();
stamper.Close();
string fn = System.IO.Path.GetFileName(name);
return base.File(name, "application/pdf",fn);
}
else
{
return View();
}
}
The problem is that you're using Ajax. You can't download a file through Ajax. You need to do a regular POST to the ActionMethod. That way the browser can send you back the file and prompt the user where he wants to save it.
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();
}
Our ASP.NET MVC 3 application is running on Azure and using Blob as file storage. I have the upload part figured out.
The View is going to have the File Name, which, when clicked will prompt the file download screen to appear.
Can anyone tell me how to go about doing this?
Two options really... the first is to just redirect the user to the blob directly (if the blobs are in a public container). That would look a bit like:
return Redirect(container.GetBlobReference(name).Uri.AbsoluteUri);
If the blob is in a private container, you could either use a Shared Access Signature and do redirection like the previous example, or you could read the blob in your controller action and push it down to the client as a download:
Response.AddHeader("Content-Disposition", "attachment; filename=" + name); // force download
container.GetBlobReference(name).DownloadToStream(Response.OutputStream);
return new EmptyResult();
Here's a resumable version (useful for large files or allowing seek in video or audio playback) of private blob access:
public class AzureBlobStream : ActionResult
{
private string filename, containerName;
public AzureBlobStream(string containerName, string filename)
{
this.containerName = containerName;
this.filename = filename;
this.contentType = contentType;
}
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
var request = context.HttpContext.Request;
var connectionString = ConfigurationManager.ConnectionStrings["Storage"].ConnectionString;
var account = CloudStorageAccount.Parse(connectionString);
var client = account.CreateCloudBlobClient();
var container = client.GetContainerReference(containerName);
var blob = container.GetBlockBlobReference(filename);
blob.FetchAttributes();
var fileLength = blob.Properties.Length;
var fileExists = fileLength > 0;
var etag = blob.Properties.ETag;
var responseLength = fileLength;
var buffer = new byte[4096];
var startIndex = 0;
//if the "If-Match" exists and is different to etag (or is equal to any "*" with no resource) then return 412 precondition failed
if (request.Headers["If-Match"] == "*" && !fileExists ||
request.Headers["If-Match"] != null && request.Headers["If-Match"] != "*" && request.Headers["If-Match"] != etag)
{
response.StatusCode = (int)HttpStatusCode.PreconditionFailed;
return;
}
if (!fileExists)
{
response.StatusCode = (int)HttpStatusCode.NotFound;
return;
}
if (request.Headers["If-None-Match"] == etag)
{
response.StatusCode = (int)HttpStatusCode.NotModified;
return;
}
if (request.Headers["Range"] != null && (request.Headers["If-Range"] == null || request.Headers["IF-Range"] == etag))
{
var match = Regex.Match(request.Headers["Range"], #"bytes=(\d*)-(\d*)");
startIndex = Util.Parse<int>(match.Groups[1].Value);
responseLength = (Util.Parse<int?>(match.Groups[2].Value) + 1 ?? fileLength) - startIndex;
response.StatusCode = (int)HttpStatusCode.PartialContent;
response.Headers["Content-Range"] = "bytes " + startIndex + "-" + (startIndex + responseLength - 1) + "/" + fileLength;
}
response.Headers["Accept-Ranges"] = "bytes";
response.Headers["Content-Length"] = responseLength.ToString();
response.Cache.SetCacheability(HttpCacheability.Public); //required for etag output
response.Cache.SetETag(etag); //required for IE9 resumable downloads
response.ContentType = blob.Properties.ContentType;
blob.DownloadRangeToStream(response.OutputStream, startIndex, responseLength);
}
}
Example:
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); // force download
return new AzureBlobStream(blobContainerName, filename);
I noticed that writing to the response stream from the action method messes up the HTTP headers. Some expected headers are missing and others are not set correctly.
So instead of writing to the response stream, I get the blob content as a stream and pass it to the Controller.File() method.
CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
Stream blobStream = blob.OpenRead();
return File(blobStream, blob.Properties.ContentType, "FileName.txt");