Andy E đúng rằng không có cách nào dựa trên HTML để thực hiện việc này *; nhưng nếu bạn sẵn sàng sử dụng Flash, bạn có thể làm được. Phần sau hoạt động đáng tin cậy trên các hệ thống đã cài đặt Flash. Nếu ứng dụng của bạn cần hoạt động trên iPhone, thì tất nhiên bạn sẽ cần một giải pháp dựa trên HTML dự phòng.
* ( Cập nhật 4/22/2013: HTML hiện hỗ trợ điều này, trong HTML5. Xem các câu trả lời khác.)
Tải lên flash cũng có những ưu điểm khác - Flash cung cấp cho bạn khả năng hiển thị thanh tiến trình khi quá trình tải lên một tệp lớn đang diễn ra. (Tôi khá chắc chắn đó là cách Gmail thực hiện, bằng cách sử dụng Flash đằng sau hậu trường, mặc dù tôi có thể sai về điều đó.)
Đây là một ứng dụng Flex 4 mẫu cho phép người dùng chọn một tệp, sau đó hiển thị nó:
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx" minWidth="955" minHeight="600"
creationComplete="init()">
<fx:Declarations>
</fx:Declarations>
<s:Button x="10" y="10" label="Choose file..." click="showFilePicker()" />
<mx:Image id="myImage" x="9" y="44"/>
<fx:Script>
<![CDATA[
private var fr:FileReference = new FileReference();
// Called when the app starts.
private function init():void
{
// Set up event handlers.
fr.addEventListener(Event.SELECT, onSelect);
fr.addEventListener(Event.COMPLETE, onComplete);
}
// Called when the user clicks "Choose file..."
private function showFilePicker():void
{
fr.browse();
}
// Called when fr.browse() dispatches Event.SELECT to indicate
// that the user has picked a file.
private function onSelect(e:Event):void
{
fr.load(); // start reading the file
}
// Called when fr.load() dispatches Event.COMPLETE to indicate
// that the file has finished loading.
private function onComplete(e:Event):void
{
myImage.data = fr.data; // load the file's data into the Image
}
]]>
</fx:Script>
</s:Application>