Качественное решение Node.js / JavaScript см. В модуле id-shorttener , который тщательно протестирован и уже несколько месяцев используется в производстве.
Он обеспечивает эффективное сокращение идентификатора / URL-адреса при поддержке сменного хранилища по умолчанию Redis , и вы даже можете настроить свой короткий набор символов идентификатора и определить, является ли сокращение идемпотентным . Это важное различие, которое учитывают не все сокращатели URL-адресов.
В отношении других ответов здесь, этот модуль реализует превосходный принятый ответ Марселя Джекверта выше.
В основе решения лежит следующий фрагмент Redis Lua :
local sequence = redis.call('incr', KEYS[1])
local chars = '0123456789ABCDEFGHJKLMNPQRSTUVWXYZ_abcdefghijkmnopqrstuvwxyz'
local remaining = sequence
local slug = ''
while (remaining > 0) do
local d = (remaining % 60)
local character = string.sub(chars, d + 1, d + 1)
slug = character .. slug
remaining = (remaining - d) / 60
end
redis.call('hset', KEYS[2], slug, ARGV[1])
return slug
Попробуйте
Server.MapPath(FileUpload1.FileName);
Изменить: В этом ответе описывается, как получить путь к файлу на сервере. В нем не описывается, как получить путь к файлу на клиенте, что и было задано в вопросе. Ответ на этот вопрос - «вы не можете», потому что современный браузер не сообщает вам путь на клиенте по соображениям безопасности.
You can't get full path of a file at client's machine. Your code might work at localhost because your client and the server is the same machine and the file is at the root directory. But if you run it on a remote machine you will get an exception.
FileUpload никогда не предоставит вам полный путь из соображений безопасности.
IE 7 и предыдущие версии отправляли на сервер полный путь к загруженному файлу, связанный с полем input type = "file"
. Firefox и другие современные браузеры считают это недостатком безопасности и не считают. Однако, похоже, это было исправлено в IE 8.
Возможно, вместо этого вам следует оценить, почему вам нужен полный путь к файлу, так как он был расположен в системе клиента. Я считаю, что это действительно лишняя информация, которую вообще нельзя публиковать. Все, что вас должно беспокоить, - это имя файла, чтобы вы могли сохранить файл, не меняя его имени.
Perhaps you misunderstand the way FileUpload
works.
When you upload a file, it is effectively being transferred from the client's computer to the server hosting your application. If you're developing the application, most times, both client and server are the same machine (your computer). Once the application is deployed however, there could be any number of clients connecting to the server, each uploading a different file.
Knowing the full path of the file on the client's computer usually isn't necessary - you'll often want to do something with the file contents. Your examples seem like ASP.NET C#, so I'm guessing you're using the FileUpload control. You can get at the uploaded file's contents by reading the raw stream (FileUpload.PostedFile.InputStream
) or by saving the file first (FileUpload.PostedFile.SaveAs
), then accessing the saved file. It's your responsibility to save the file, if you want it to be accessible after the current request - if you don't, ASP.NET deletes it.
One more thing - don't forget to set the enctype
property on your form to "multipart/form-data". If you don't, the client's browser won't send the file, and you'll spend quite a few minutes wondering what went wrong.
It's currently true that "when you upload a file the browser will only send the source filename and not the full path" - it makes perfect sense that the server has no business knowing whether the file was in "C:\WINDOWS\" or "F:\SOMEDIR\OTHERDIR\PERSONALINFO\". The filename is always sent, and is useful both to help the user 'recognise' the content and possibly to interrogate the file extension to help determine the file type.
However I know from experience that Internet Explorer definitely used to (in older versions) send the entire path. It's difficult to find an authoritative confirmation (except this apache fileupload control doco)
Internet Explorer provides the entire path to the uploaded file and not just the base file name
Regardless, you should not use nor expect the full path to be sent by any 'modern' browser.
Просто чтобы отдать свои 2 цента.
В этот момент я также ДОЛЖЕН получить полный локальный путь пользователя. Я могу воспроизвести эту проблему только с 1 машины, но она действительно дает полный путь к файлу на машине пользователя.
Это конечный пользователь нашего приложения, размещенного на стороннем сервере. Таким образом, он не находится ни на локальном компьютере, ни на локальном сервере, с которого он может быть общим.
Вы можете решить проблему, по крайней мере, чтобы иметь одно и то же поведение все время следующим образом:
Path.GetFileName(fileUpload.FileName)
Кстати, просто нашел эту статью, в которой говорится, что это тоже может произойти: http://www.eggheadcafe.com/community/aspnet/17/10092650/fileupload-control-pro.aspx
Просто чтобы подтвердить проблему.
I had sort of the opposite issue as the original poster: I was getting the full path when I only wanted the filename. I used Gabriël's solution to get just the filename, but in the process I discovered why you get the full path on some machines and not others.
Any computer joined to domain will give you back the full path for the filename. I tried this on several different computers with consistent results. I don't have an explanation for why, but at least in my testing it was consistent.
As of IE8, the full path is no longer sent to sites in the Internet Zone.
See the "File Upload Control" section at the end of this post: http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx for discussion.
Я использую IE 8 (на двух разных машинах). Каждый по-прежнему загружает полный путь к локальному файлу. Как предложил Габриэль, Path.GetFileName (fileUploadControl.PostedFile.FileName) кажется единственным способом гарантировать, что вы получите только имя файла.