2012-06-28 2 views
1

Я хочу загрузить файл с помощью jQuery и сохранить его в папке на сервере. Я не знаю, с чего начать. Путь к файлу также должен храниться в базе данных Oracle. Весь мой сценарий основан на платформе Entity Framework. Кто-нибудь знает, как это решить?Как загрузить файл с помощью jquery?

+0

Посещение http://stackoverflow.com/questions/4668086/ any-plugin-to-upload-file [1]: –

ответ

0

вы можете загрузить файл легко с помощью IFRAME в jquery, если вы не хотите использовать какой-либо плагин. Я столкнулся с этой проблемой со многих дней, и теперь я решил это.

$(document).ready(function() { 
    $("#formsubmit").click(function() {  

     var iframe = $('<iframe name="postframe" id="postframe" class="hidden" src="about:none" />');   

     $('div#iframe').append(iframe);   

     $('#theuploadform').attr("action", "/ajax/user.asmx/Upload") 
     $('#theuploadform').attr("method", "post") 
     $('#theuploadform').attr("userfile", $('#userfile').val()) 
     $('#theuploadform').attr("enctype", "multipart/form-data") 
     $('#theuploadform').attr("encoding", "multipart/form-data") 
     $('#theuploadform').attr("target", "postframe")   
     $('#theuploadform').submit(); 
     //need to get contents of the iframe 
     $("#postframe").load(
      function() { 
       iframeContents = $("iframe")[0].contentDocument.body.innerHTML; 
       $("div#textarea").html(iframeContents); 
      } 
     ); 



<div id="uploadform"> 
    <form id="theuploadform" action=""> 
     <input id="userfile" name="userfile" size="50" type="file" /> 
     <input id="formsubmit" type="submit" value="Send File" /> 
    </form> 
</div> 

<div id="iframe" style="width: 0px; height: 0px; display: none;"> 
</div> 

<div id="textarea"> 
</div> 

Будет загружен файл. Теперь осталось только получить этот файл на вашем сервере. Я использовал сервлет для получения файла, после чего я назвал одну услугу. Этот пример будет работать для каждого файла изображения, текст, DOCX, документ и т.д.

Servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 
try { 
    ServletFileUpload upload = new ServletFileUpload(); 
    response.setContentType("text/plain"); 
    //response.setContentType("application/msword"); 


    FileItemIterator iterator = upload.getItemIterator(request); 

    while (iterator.hasNext()) { 
     FileItemStream item = iterator.next(); 
     String filename = item.getName(); 
     InputStream stream = item.openStream(); 
     //more here you wanna to do with that file do. 
    } 
} 
catch (FileUploadException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
} 

Наслаждайтесь ...

Смежные вопросы