如何上传文件并保存到目录?

时间:2016-08-02 07:33:00

标签: javascript jquery file-upload

HTML

<div style="width:200px">
<form action="javascript:_bulkUser();" method="post" enctype="multipart/form-data">  
    Select File:<input type="file" name="fname"/><br/>  
    <input type="submit" value="upload"/>  
</form>

</div>

js(ajax call)

_bulkUser : function(scope) {
    try {
        $.ajax({
            type : "post",
            url : "FileUploadServlet",
            success : function(data) {
                alert('Sucess');
            },
            error : function(data) {
                console.log(data);
            }
        });
    } catch (e) {
        console.log(e);
    }
}

的Servlet

protected void  doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html"); 
    PrintWriter out = response.getWriter(); 
    System.out.println("working");
    MultipartRequest mp = new MultipartRequest(request, "e:/new");
    out.print("successfully uploaded"); 
}

2 个答案:

答案 0 :(得分:-1)

到目前为止,从jQuery使用的当前XMLHttpRequest版本1开始,无法通过XMLHttpRequest使用JavaScript上载文件。常见的解决方法是让JavaScript创建一个隐藏的并将表单提交给它,以便创建它以异步方式发生的印象。这也是大多数jQuery文件上传插件正在执行的操作,例如jQuery Form插件(例如此处)。

假设您的带有HTML表单的JSP以这样的方式重写,以便在客户端禁用JS时(例如现在......)不会破坏它,如下所示:

<form id="upload-form" class="upload-box" action="/Upload" method="post" enctype="multipart/form-data">
    <input type="file" id="file" name="file1" />
    <span id="upload-error" class="error">${uploadError}</span>
    <input type="submit" id="upload-button" value="upload" />
</form>

然后在jQuery Form插件的帮助下只需

<script src="jquery.js"></script>
<script src="jquery.form.js"></script>
<script>
    $(function() {
        $('#upload-form').ajaxForm({
            success: function(msg) {
                alert("File has been uploaded successfully");
            },
            error: function(msg) {
                $("#upload-error").text("Couldn't upload file");
            }
        });
    });
</script>

对于servlet方面,这里不需要做任何特殊的事情。只需像不使用Ajax时那样实现它:How to upload files to server using JSP/Servlet?

如果X-Requested-With标头等于或不是XMLHttpRequest,您只需要在servlet中进行额外检查,这样您就知道在客户端禁用JS的情况下如何返回何种响应(如现在,它主要是旧的移动浏览器,它们已禁用JS)。

if ("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))) {
    // Return ajax response (e.g. write JSON or XML).
} else {
    // Return regular response (e.g. forward to JSP).
}

请注意,相对较新的XMLHttpRequest版本2能够使用新的File和FormData API发送选定的文件。另请参阅HTML5文件上载到Java Servlet并通过xmlHttpRequest将文件作为multipart发送。

答案 1 :(得分:-1)

此代码也适用于我:

$('#fileUploader').on('change', uploadFile);


function uploadFile(event)
    {
        event.stopPropagation(); 
        event.preventDefault(); 
        var files = event.target.files; 
        var data = new FormData();
        $.each(files, function(key, value)
        {
            data.append(key, value);
        });
        postFilesData(data); 
     }

function postFilesData(data)
    {
     $.ajax({
        url: 'yourUrl',
        type: 'POST',
        data: data,
        cache: false,
        dataType: 'json',
        processData: false, 
        contentType: false, 
        success: function(data, textStatus, jqXHR)
        {
            //success
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
            console.log('ERRORS: ' + textStatus);
        }
        });
    }

<form method="POST" enctype="multipart/form-data">
    <input type="file" name="file" id="fileUploader"/>
</form>