Uploading Image Access to C drive denied - asp.net

so i have this code:
try
{
if ((uplImage.FileName != ""))
{
//to allow only jpg gif and png files to be uploaded.
string extension = Path.GetExtension(uplImage.PostedFile.FileName);
if (((extension == ".jpg") || ((extension == ".gif") || (extension == ".png"))))
{
DALBio bio = new DALBio();
byte[] raw;
FileStream fs = new FileStream(uplImage.PostedFile.FileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
raw = new byte[fs.Length];
fs.Read(raw, 0, Convert.ToInt32(fs.Length));
bio.PlayerID = Session["playerID"].ToString();
bio.Pending = 'Y';
bio.Photo = raw;
DALBio.insertImage(bio);
}
}
}
catch (Exception e1)
{
Label1.Text = e1.InnerException.ToString();
}
and the program breaks on the FileStream fs = new FileStream line.
at first my image was in my downloads folder and it said access to c:\prog(x86)\filefolder\file\folder\and so on was denied
so i moved it to my images folder, and i got the same error to a different folder on c.
my google searches have said it oculd be a permissions thing (if its UAC, that makes no sense, i have all permissions possible across the board). another thing is it could be a change in my web.config file about application settings, however without any examples or better insight than what i did get from those searches, i am lost.

You have to give account under which ASP.NET worker process runs "write" permissions. Ordinary it's Network Services account.

Related

Working way to transfer SQLite database to another device without external storage permissions (updates Android 11)

With new Shared Storage and new Android API 30 requirements I can't find a way to recover a database on new or another device.
Until this time, I used File API to create a copy of the database. Any time user could put this file to any cloud, download from cloud on another device and restore the database on it. Of course, I used WRITE_EXTERNAL_STORAGE.
Now, Google rejects the app and says that we should use MediaStore API which can solve that issues without any permissions. I tried it and it works only on same device. And until if created the database file not copied to/from cloud or moved to/from another folder. In that case cursor.getCount == 0:
String[] projections = new String[]{MediaStore.Downloads._ID};
String selection = MediaStore.Downloads.DISPLAY_NAME + "=?";
String[] selectionArgs = new String[]{"database.db"};
String sortOrder = MediaStore.Downloads.DISPLAY_NAME + " ASC";
Cursor cursor = getApplicationContext().getContentResolver().query(MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL), projections, selection, selectionArgs, sortOrder);
Uri uri = null;
if (cursor != null) {
int idColumn = cursor.getColumnIndexOrThrow(MediaStore.Downloads._ID);
cursor.moveToNext();
long id = cursor.getLong(idColumn);
uri = ContentUris.withAppendedId(MediaStore.Downloads.EXTERNAL_CONTENT_URI, id);
try {
ContentResolver contentResolver = getApplicationContext().getContentResolver();
ParcelFileDescriptor parcelFileDescriptor = contentResolver.openFileDescriptor(uri, "rw");
FileInputStream fileInputStream = new FileInputStream(parcelFileDescriptor.getFileDescriptor());
File dbFile = new File(Environment.getDataDirectory(), "/data/com.example.app/databases/database.db");
FileOutputStream fileOutputStream = new FileOutputStream(dbFile);
byte[] buf = new byte[1024];
int len;
while ((len = fileInputStream.read(buf)) > 0) {
fileOutputStream.write(buf, 0, len);
}
fileOutputStream.close();
fileInputStream.close();
parcelFileDescriptor.close();
restartApp();
} catch (IOException e) {
e.printStackTrace();
}
cursor.close();
}
Something wrong with code or MediaStore API does not provide any actions with created files?
E/DBError: exception
android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0
Also I tried Google Drive API to copy the database file on cloud directly from app and download it. But it's not working way too, because new device don't know about file ID which used to download files.
Any thoughts on this?
Figured out.
Without any storage permissions your app have access to onw created files with MediaStore API.
But haven't if:
file was moved/copied inside device storage
file was uploaded to cloud and then downloaded from it
app was reinstalled
I tested it on versions 28 (emulation), 29 (device), 30 (emulation).
So in my case anyway I need:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="29"/>
Don't know why but for read own file on Android Q not enough only READ_EXTERNAL_STORAGE
I was lucky and Google approved app. Hope you too.

WAS Liberty Profile won't run external process (using Runtime.getRuntime().exec(cmd) )

As the title suggests, WLP won't run the process- it won't return anything to the process input stream nor to error stream.
If anyone knows about a configuration that needs to take place I would love to know..
(note the process Can run by running the command manually - in addition, the whole thing runs smooth on tomcat8 so..)
EDIT 1:
The problem was not the command execution under WLP as you guys stated, so I accepted the answer.
The problem is different : I sent a media file to a multipart servlet and stored it in a file on disk using the following code:
InputStream is = request.getInputStream();
String currentTime = new Long(System.currentTimeMillis()).toString();
String fileName = PATH + currentTime + "." + fileType;
File file = new File(fileName);
// write the image to a temporary location
FileOutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[BUFFER_SIZE];
while(true) {
int numRead = is.read(buffer);
if(numRead == -1) {
break;
}
os.write(buffer, 0, numRead);
os.flush();
}
is.close();
os.close();
and the file gets saved along with the following prefix:
While this does not happen on tomcat8 (using the same client)..
something is not trivial in the received input stream. (Note its a multipart servlet that set up via #MultipartConfig only)
Hope this post will help others..
guys,thanks for your help!
This will work in Liberty. I was able to test out the following code in a servlet and it printed the path of my current directory just fine:
String line;
Process p = Runtime.getRuntime().exec("cmd /c cd");
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
System.out.println(line);
}
input.close();
Start with a simple command like this, and when you move up to more complex commands or scripts, make sure you are not burying exceptions that may come back. Always at least print the stack trace!

Cannot upload large (>50MB) files to SharePoint 2010 document library

I'm trying to upload a large file to a document library, but it fails after just a few seconds. The upload single document fails silently, upload multiple just shows a failed message. I've turned up the file size limit on the web application to 500MB, and the IIS request length to the same (from this blog), and increased the IIS timeout for good measure. Are there any other size caps that I've missed?
Update I've tried a few files of various sizes, anything 50MB or over fails, so I assume something somewhere is still set to the webapp default.
Update 2 Just tried uploading using the following powershell:
$web = Get-SPWeb http://{site address}
$folder = $web.GetFolder("Site Documents")
$file = Get-Item "C:\mydoc.txt" // ~ 150MB
$folder.Files.Add("SiteDocuments/mydoc.txt", $file.OpenRead(), $false)
and get this exception:
Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://{site address}/SiteDocuments/mydoc.txt' in this Web."
which strikes me as odd as of course the file wouldn't exist until it's been uploaded? N.B. while the document library has the name Site Documents, it has the URL SiteDocuments. Not sure why...
Are you sure you updated the right webapp? Is the filetype blocked by the server? Is there adequate space in your content database? I would check ULS logs after that and see if there is another error since it seems you hit the 3 spots you would need too update.
for uploading a large file, you can use the PUT method instead of using the other ways to upload a document.
by using a put method you will save the file into content database directly. see the example below
Note: the disadvantage of the code below is you cannot catch the object that is responsible for uploading directly, on other word, you cannot update the additional custom properties of the uploaded document directly.
public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = “PUT”;
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
}
//Return the final upload status
return isUploaded;
}
and here are an example of calling this method
UploadFileToDocumentLibrary(#”C:\test.txt”, #”http://home-vs/Shared Documents/textfile.pdf”);

Itext, access denied on htmlworker.parseToList

I have spent far too long trying to work out why I am getting an access denied here so I am
really hoping someone can help?
I am using itextsharp, the latest version downloaded today.
I am parsing an html page within my own project so I can convert it to pdf, but everytime I run
it I get an access denied on path c:\
For starters I cannot work out why it's trying to access the c drive other than the website directory which it definitely has access to.
And I have tried adding network service with full permission to everything but it didn't work.
I even impersonated an admin user in the web config but I still got access denied.
My code is:
string download = new WebClient().DownloadString("http://" + HttpContext.Current.Request.Url.Host + "/pagetoparse.aspx?user=" + userName);
string tempFolder = HttpContext.Current.Server.MapPath("pdfs");
if (!Directory.Exists(tempFolder))
{
Directory.CreateDirectory(tempFolder);
}
string fileName = Path.Combine(tempFolder, "test3.pdf");
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
try
{
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(fileName, FileMode.Create));
using (StringReader stringReader = new StringReader(download))
{
List<IElement> parsedList = HTMLWorker.ParseToList(stringReader, null);//<-- fails here!
document.Open();
foreach (object item in parsedList)
{
document.Add((IElement)item);
}
document.Close();
}
}
catch (Exception exc)
{
Console.Error.WriteLine(exc.Message);
}
return document;
It must be obvious, what I am doing wrong??
Bex
Arrrgh! And the answer is:
An empty image tag! It tried to parse it as a path!!

FileUpload problem with Struts on server

I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.

Resources