string? folder = _dirSettings.PostImageDir;
List<PostImage> postImages = new();
if (!string.IsNullOrEmpty(folder))
{
string[] folderPaths = folder.Split("/");
string[] fileExtentions = new[]{
".pdf",
".png",
".jpeg",
"jpg"
};
await using ApplicationDbContext dbContext =
_dbContextFactory.CreateDbContext();
foreach (var file in files)
{
string fileName = System.IO.Path.GetFileNameWithoutExtension(file.Name);
string fileExtn = System.IO.Path.GetExtension(file.Name);
if(!fileExtentions.Contains(fileExtn))
{
throw new Exception("only Can Add pdf, png, jpeg, jpg");
}
var postImage = new PostImage()
{
Title = fileName,
ImageUri = new Uri(new Uri("file://"),folder + "/" + Guid.NewGuid().ToString() + "_" + file.Name),
PostId = postId
};
string serverFolderPath = _webHostEnvironment.ContentRootPath;
foreach (var path in folderPaths)
{
serverFolderPath = System.IO.Path.Combine(serverFolderPath, path);
}
using (var fileStream = new FileStream(serverFolderPath, FileMode.Create))
{
await file.CopyToAsync(fileStream);
}
postImages.Add(postImage);
}
await dbContext.AddRangeAsync(postImages);
await dbContext.SaveChangesAsync();
when I run this code it show Access to the path 'D:\Web\GraphQL\Files\PostImages' is denied.
I already Added all permission to Users. and unchecked readonly to folder.
how can I fix it? thank you.
Related
After upload images to azure blob the images look like https://dodealstorge.blob.core.windows.net/upload/2021-03-31/20210331T071342445.jpg is not uploading the right img ,I changed container access level to public in Azure portal
this is the code:
private async Task<string> UploadFileToBlobAsync(string strFileName, byte[] fileData, string fileMimeType)
{
if (fileName != null && fileData != null)
{
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(fileName);
cloudBlockBlob.Properties.ContentType = fileMimeType;
await cloudBlockBlob.UploadFromByteArrayAsync(fileData, 0, fileData.Length);
return cloudBlockBlob.Uri.AbsoluteUri;
}
return "";
}
}
Controller :
var fileName = Path.GetFileName(photoIform.FileName);
var fileStream = new FileStream(Path.Combine(uploads, photoIform.FileName), FileMode.Create);
string mimeType = photoIform.ContentType;
byte[] fileData = new byte[photoIform.Length];
// Update
photoIform.OpenReadStream();
BlobStorageService objBlobService = new BlobStorageService();
img2.ImgPath = objBlobService.UploadFileToBlob(photoIform.FileName, fileData, mimeType);
I am trying to upload a csv file that is created from a query and upload via sftp.
I am trying to avoid creating a file and then reading the file to upload it by keeping the data in memory.
Thanks in advance
var customerAddresses = addresses.Select(p => new { p.Customer.Name, p.Customer.AlternateName, p.City, p.StateProvince });
using (var memoryStream = new MemoryStream())
{
//if you pass a file path to streamWriter it creates a csv with the correct format and data
using (var streamWriter = new StreamWriter())
{
using (var csv = new CsvWriter(streamWriter))
{
csv.WriteRecords(customerAddresses);
var fileName = DateTime.UtcNow.ToString(dateFromat) + destinationFileName;
var privateKey = new PrivateKeyFile(sshKeyLocation);
var connectionInfo = new PrivateKeyConnectionInfo(address,
username,
new PrivateKeyFile(sshKeyLocation)
);
memoryStream.Flush();
using (var client = new SftpClient(connectionInfo))
{
client.Connect();
client.ChangeDirectory(serverDirectory);
client.UploadFile(memoryStream, fileName); //is always an empty file
}
}
}
Try adding setting memoryStream Position to beginning with Seek before calling UploadFile and calling streamWriter.Flush();, not memoryStream.Flush():
streamWriter.Flush();
memoryStream.Seek(0, SeekOrigin.Begin);
using (var client = new SftpClient(connectionInfo))
{
client.Connect();
client.ChangeDirectory(serverDirectory);
client.UploadFile(memoryStream, fileName);
}
I never figured out how to get it to work with MemoryStream and changed to to write a file and then read and upload that file.
public HttpResponseMessage Post([FromBody] CustomerIds[] CustomerIds)
{
try
{
if(CustomerIds.Length == 0)
{
throw new Exception("No customer ids passed in post body.");
}
else if (!File.Exists(sshKeyLocation))
{
throw new Exception("Missing ssh file.");
}
if(!Directory.Exists(localDirectory))
{
Directory.CreateDirectory(localDirectory);
}
var customerAddresses = _repository.GetPrimaryAddress(CustomerIds.Select(c => c.Id))
.Select(p => new
{
p.Customer.Name,
p.Customer.AlternateName,
p.City,
p.StateProvince
}
);
if (customerAddresses == null || !customerAddresses.Any())
{
throw new Exception("No customer addresses found for selected customers.");
}
var fileName = DateTime.UtcNow.ToString(dateFromat) + destinationFileName;
var localFilePath = Path.Combine(localDirectory, fileName);
CreateFile(customerAddresses, localFilePath);
UploadFile(localFilePath, fileName);
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
catch(Exception error)
{
logger.Error(error, error.Message);
throw error;
}
}
private void CreateFile(IEnumerable<object> customerAddresses, string filePath)
{
using (TextWriter streamWriter = new StreamWriter(filePath))
using (var csv = new CsvWriter(streamWriter))
{
csv.WriteRecords(customerAddresses);
}
}
private void UploadFile(string localFilePath, string destinationFileName)
{
var connectionInfo = new PrivateKeyConnectionInfo(address,
username,
new PrivateKeyFile(sshKeyLocation)
);
using (var fileStream = new FileStream(localFilePath, FileMode.Open))
using (var client = new SftpClient(connectionInfo))
{
client.Connect();
client.ChangeDirectory(serverDirectory);
client.UploadFile(fileStream, destinationFileName);
}
}
I've run out of time to continue trying to upload using the MemoryStream and will just have to use this solution. Disappointed I couldn't get it to work.
I want to send image files to SQL Server using C#.
The below code is working and saving files and their paths into the database. I need the same data in my API endpoint's response. I've created a custom response class, called RegistrationResponse.
I'm beginner in this so I'm looking for help.
public async Task<RegistrationResponse> PostFormData(HttpRequestMessage request)
{
object data = "";
NameValueCollection col = HttpContext.Current.Request.Form;
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/images");
var provider = new MultipartFormDataStreamProvider(root);
// Read the form data and return an async task.
var task = Request.Content.ReadAsMultipartAsync(provider).
ContinueWith<HttpResponseMessage>(t =>
{
if (t.IsFaulted || t.IsCanceled)
{
Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
}
//read file data
foreach (MultipartFileData dataItem in provider.FileData)
{
try
{
string description = string.Empty;
string userId = string.Empty;
String fileName = string.Empty;
// Show all the key-value pairs.
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in provider.FormData.GetValues(key))
{
if (key.ToString().ToLower() == "userid")
{
userId = val;
}
else if (key.ToString().ToLower() == "description")
{
description = val;
}
}
}
String name = dataItem.Headers.ContentDisposition.FileName.Replace("\"", "");
fileName = userId + Path.GetExtension(name);
File.Move(dataItem.LocalFileName, Path.Combine(root, fileName));
using (var db = new AlumniDBEntities())
{
//saving path and data in database table
Post userPost = new Post();
userPost.Files = fileName;
userPost.Description = description;
userPost.UserID = Convert.ToInt32(userId);
userPost.CreatedDate = DateTime.Now;
db.Posts.Add(userPost);
db.SaveChanges();
data = db.Posts.Where(x => x.PostID ==
userPost.PostID).FirstOrDefault();
string output = JsonConvert.SerializeObject(data);
}
}
catch (Exception ex)
{
return Request.CreateResponse(ex);
}
}
return Request.CreateResponse(HttpStatusCode.Created);
});
var response = new RegistrationResponse
{
success = true,
status = HttpStatusCode.OK,
message = "Success",
data = data
};
return response;
}
public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
WebClient webClient = new WebClient();
byte[] responseBinary = webClient.UploadFile(apiUrl, file.FileName);
string response = Encoding.UTF8.GetString(responseBinary);
/* Giving error here. How to proceed?
}
I want to upload a single file to this url and the response is shown in the figure above. How to proceed further with the same in C#? Please help
Try your code like below.
public ActionResult Index(PublishPost post, HttpPostedFileBase file)
{
var apiURL = "http://test.sa.com/rest/social/update/1161/upload?access_token=6fWV564kj3drlu7rATh8="
using (HttpClient client = new HttpClient())
{
using (var content = new MultipartFormDataContent())
{
byte[] fileBytes = new byte[file.InputStream.Length + 1];
file.InputStream.Read(fileBytes, 0, fileBytes.Length);
var fileContent = new ByteArrayContent(fileBytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
content.Add(fileContent);
var result = client.PostAsync(apiURL, content).Result;
if (result.StatusCode == System.Net.HttpStatusCode.OK)
{
return new
{
code = result.StatusCode,
message = "Successful",
data = new
{
success = true,
filename = file.FileName
}
};
}
else
{
return new
{
code = result.StatusCode,
message = "Error"
};
}
}
}
}
this is my javascript code :
var fileURL = "file://" + mFileListURL[0].fullPath;
var options = new FileUploadOptions();
options.fileKey = "recFile";
var imagefilename = Number(new Date()) + ".jpg";
options.fileName = imagefilename;
options.mimeType = "image/jpeg";
var params = new Object();
options.params = params;
var ft = new FileTransfer();
ft.upload(fileURL,"http://mywebserver/UploadFoto.asmx/SaveImage",
function(r) {
alert("It's OK!");
alert("Response = " + r.response);
}, function(error) {
alert("An error has occurred: Code = "
+ error.code);
}, options);
and this server side code:
[WebMethod]
[GenerateScriptType(typeof(String))]
[ScriptMethod]
public String SaveImage()
{
HttpContext context = HttpContext.Current;
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
foreach (string key in files)
{
HttpPostedFile file = files[key];
string fileName = file.FileName;
if (fileName != null && fileName != "")
{
String fileStored = System.IO.Path.Combine(context.Server.MapPath("~/public/"), fileName);
file.SaveAs(fileStored);
}
}
}
return "Filestored OK";
}
Now, image upload is done but I get no returned string, no response from server, no error code. I used Json response also but nothing (image is upload, no response, no string returned).
What's wrong?
Thanks. IngD
try this
function(r)
{
alert("It's OK!");
alert("Sent = " + r.bytesSent);
}
WebMethod Must be static
[WebMethod]
[GenerateScriptType(typeof(String))]
[ScriptMethod]
public static String SaveImage()
{
HttpContext context = HttpContext.Current;
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
foreach (string key in files)
{
HttpPostedFile file = files[key];
string fileName = file.FileName;
if (fileName != null && fileName != "")
{
String fileStored = System.IO.Path.Combine(context.Server.MapPath("~/public/"), fileName);
file.SaveAs(fileStored);
}
}
}
return "Filestored OK";
}