My folder structure is webapp-->resource--> images.
Here is my code:
public String addProductPost(#ModelAttribute("products") Product product, HttpServletRequest request) {
productDao.addProduct(product);
System.out.println(product);
MultipartFile productImage = product.getProductImage();
String rootDirectory = request.getSession().getServletContext().getRealPath("/");
path = Paths.get(rootDirectory +"webapp/resources/image"+ product.getProductId()+".png");
if (productImage !=null && !productImage.isEmpty()) {
try {
productImage.transferTo(new File(path.toString()));
/*Files.copy(Paths.get(productImage.toString()), path);*/
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("Product image saving failed ", e);
}
}
Did you try System.out.println(path); ? If you're not getting any error then the image is getting saved in the said directory but doesn't show up in eclipse project manager. To see the image, navigate to the folder where you have said the image.
Related
I am trying to upload image to the server with WebAPI
C# Code:
public async Task<string> Post()
{
try
{
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
foreach(string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filename = postedFile.FileName.Split('\\').LastOrDefault().Split('/').LastOrDefault();
var filePath = HttpContext.Current.Server.MapPath("~/Uploads/"+ filename);
postedFile.SaveAs(filePath);
return "/uploads" + filename;
}
}
else
{
return "file was not uploaded";
}
}
catch (Exception exception)
{
return exception.Message;
}
return "hi";
}
When I upload image through postman, I get
"Access to the path 'c:\users\ahmed\source\repos\Election\Election\Uploads\Background.png' is denied."
Check your upload folder permissions. And add everyone permission to upload folder, and test it again. Don't forget remove everyone permission when test is over.
I am receiving the following runtime-error when attempting to load an image via ImageSource assignment.
Cannot use the specified Stream as a Windows Runtime IRandomAccessStream because this Stream does not support seeking.
Specifically, I am passing an ImageSource object from one page to another page.
Thus, I am surprised that I am receiving this error.
I have even tried extracting the stream object from the ImageSource object.
However, this does not appear to be supported.
Can anyone provide guidance on how I can resolve this issue?
Same problem i was facing,
Please follow following step.
1.In your xaml page add like this a img tag
Image x:Name="productImage" Source="{Binding SelectedSalesItem.Source}"
2. on any grid call ItemSelected="OnSalesItemSelected" event called bellow method.
Public async void OnSalesItemSelected(object sender, EventArgs args) {
try
{
if (SaleVm.SelectedSalesItem != null)
{
OnImages();//Call point no 3 method "OnImages"
}
}
catch (Exception ex)
{
throw ex;
}
}
3.Create a method in your xaml.cs page.
async void OnImages() {
try
{
if (SaleVm.SelectedSalesItem != null)
{
IFolder rootFolder = FileSystem.Current.LocalStorage;
IFolder imageFolder = await rootFolder.GetFolderAsync("ItemsImg");
IFile imageFile = await imageFolder.GetFileAsync(SaleVm.SelectedSalesItem.ItemCode + ".png");
var stream = await imageFile.OpenAsync(FileAccess.Read);
productImage.Source = ImageSource.FromStream(() => stream);
}
}
catch (Exception ex)
{
throw ex;
}
}
4. Call "OnImages()" method from other class like ViewModel.
and change image at run time.
I've got a working website that I can upload and download files to a folder within the project locally. However when I use IIS to host the website across LAN, I get a 404 error when trying to download files - I can upload the files fine and they appear in the correct folder.
Error:
HTTP Error 404.0 - Not Found The resource you are looking for has been
removed, had its name changed, or is temporarily unavailable.
Here are my controllers.
Download controller:
[HttpGet]
public virtual ActionResult Download(string file)
{
string fullPath = Path.Combine(Server.MapPath("~/SupportAttachments/"), file);
return File(fullPath, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", file);
}
Upload Controller:
[HttpPost]
public JsonResult UploadFiles(string id)
{
try
{
foreach (string file in Request.Files)
{
var hpf = Request.Files[file] as HttpPostedFileBase;
if (hpf.ContentLength == 0)
continue;
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
// get a stream
var stream = fileContent.InputStream;
// and optionally write the file to disk
var fileName = id + " " + hpf.FileName;
var path = Path.Combine(Server.MapPath("~/SupportAttachments/"), Path.GetFileName(fileName));
// Save the file
hpf.SaveAs(path);
}
}
}
catch (Exception)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return this.Json("Upload failed");
}
return this.Json("File uploaded successfully");
}
Can anyone advise me as to why I can't download files when hosting via IIS?
I implemented a functions in AJAXControlToolkit to allow upload of image, but once I uploaded the image, it become not able to open (originally it open without problem in my PC). Note that however, some of the files uploaded without problem.
Below is the upload code
protected void tbxContent_HtmlEditorExtender_ImageUploadComplete(object sender, AjaxControlToolkit.AjaxFileUploadEventArgs e)
{
try
{
string storage = #"/storage/";
string filename = DateTime.Now.Ticks.ToString() + e.FileName.Substring(e.FileName.IndexOf('.'));
if (!Directory.Exists(Server.MapPath(storage)))
{
Directory.CreateDirectory(Server.MapPath(storage));
}
// Save your File
(sender as AjaxControlToolkit.AjaxFileUpload).SaveAs(Server.MapPath(storage + filename));
// Tells the HtmlEditorExtender where the file is otherwise it will render as: <img src="" />
e.PostedUrl = storage + filename;
}
catch (Exception ex)
{
}
}
When I click on the image file at the server, I got the error as below.
Updated 1:
Seems like all the image details gone after uploaded to server, previously it exists my local PC.
I want to delete Read-only Folder. I did like this
//Remove Read-only for the Folder
File.SetAttributes(folderpath, File.GetAttributes(folderpath) & ~FileAttributes.ReadOnly);
//Delete Folder
FileInfo myfileinf = new FileInfo(folderpath);
myfileinf.Delete();
But i get this Error
"Access to the path 'E:\Working Folder\RPEssential\RPEssential\ResourcePlus-PL\RDLReports\t' is denied".
As I commented earlier the problem is that you are trying to delete a folder as you were deleting a file.
You should use Directory.Delete method to delete a folder.
In the following link there is a good example on how to use it
http://msdn.microsoft.com/en-au/library/fxeahc5f(v=vs.100).aspx
public static void Main()
{
// Specify the directories you want to manipulate.
string path = #"c:\MyDir";
string subPath = #"c:\MyDir\temp";
try
{
// Determine whether the directory exists.
if (!Directory.Exists(path))
{
// Create the directory.
Directory.CreateDirectory(path);
}
if (!Directory.Exists(subPath))
{
// Create the directory.
Directory.CreateDirectory(subPath);
}
// This will succeed because subdirectories are being deleted.
Console.WriteLine("I am about to attempt to delete {0}", path);
Directory.Delete(path, true);
Console.WriteLine("The Delete operation was successful.");
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
There can be many reasons for a read only to be denied. Is the folder in use? Open in a console? Running an executable? All of these things you should check. Even if it has the permission, if the directory is in use, it won't allow you to delete it.