请求在Java File Uploader

时间:2015-10-31 08:16:53

标签: java jquery jsp servlets file-upload

我尝试在java中创建文件上传器。这是工作,但重定向到servlet,我想这样做而不重新加载页面。所以我试过这种方式。

test.js

$(document).ready(function() {
$('#btn').click(function() {
    $.ajax({
        type: 'post',
        url : '../FileUploadServlet2',
        data : {
            picture : $('#picture').val()
        },
        success : function(responseText) {
            $('#ajaxGetUserServletResponse').text(responseText);
        }
    });
}); });

Test.jsp - body

<form id="myform" method="post" enctype="multipart/form-data">
    Enter Image: <input type="file" id="picture" />
    <input type="hidden" value="true" name="submit">
    <input id="btn" type="button" value="Click">
</form>
<br>
<br>

<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>

FileUploadServlet2

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doGet(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    processRequest(request, response);
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    System.out.println("Here");

    processRequest(request, response);

}

protected void processRequest(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    // location where file are uploaded
    String destination = "/home/dhanushka/test2";
    // creates a file in the given location

    // Create path components to save the file
    final String path = destination;
    // get the part of the profile picture file
    final Part filePart2 = request.getPart("picture");
    // gets only the file name
    final String fileName2 = getFileName(filePart2);

    // upload the profile picture
    try {
        writer = response.getWriter();
        uploadProcess(fileName2, path, filePart2);
        writer.write("Uploaded");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(content.indexOf('=') + 1).trim()
                    .replace("\"", "");
        }
    }
    return null;
}

private void uploadProcess(String fileName, String path, Part filePart)
        throws Exception {
    try {
        out = new FileOutputStream(new File(path + File.separator
                + fileName));

        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        /* writer.println("New file " + fileName + " created at " + path); */
        LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
                new Object[] { fileName, path });
    } catch (FileNotFoundException fne) {
        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        writer.println("<br/> ERROR: " + fne.getMessage());

        LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
                new Object[] { fne.getMessage() });

    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }

    }
}}

这会返回错误。

  

2015年10月31日下午1:33:24 org.apache.catalina.core.StandardWrapperValve   为servlet调用SEVERE:Servlet.service()   [com.sms.upload.FileUploadServlet2]在路径[/ SMS]的上下文中投掷   例外   [org.apache.tomcat.util.http.fileupload.FileUploadBase $ InvalidContentTypeException:   请求不包含multipart / form-data或multipart / mixed   流,内容类型标题是application / x-www-form-urlencoded;   具有根本原因的charset = UTF-8]   org.apache.tomcat.util.http.fileupload.FileUploadBase $ InvalidContentTypeException:   请求不包含multipart / form-data或multipart / mixed   流,内容类型标题是application / x-www-form-urlencoded;   charset = UTF-8 at   org.apache.tomcat.util.http.fileupload.FileUploadBase $ FileItemIteratorImpl。(FileUploadBase.java:800)     在   org.apache.tomcat.util.http.fileupload.FileUploadBase.getItemIterator(FileUploadBase.java:256)     在   org.apache.tomcat.util.http.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:280)     在   org.apache.catalina.connector.Request.parseParts(Request.java:2730)     在org.apache.catalina.connector.Request.getParts(Request.java:2641)     在org.apache.catalina.connector.Request.getPart(Request.java:2818)     在   org.apache.catalina.connector.RequestFacade.getPart(RequestFacade.java:1089)     在   com.sms.upload.FileUploadServlet2.processRequest(FileUploadServlet2.java:75)     在   com.sms.upload.FileUploadServlet2.doPost(FileUploadServlet2.java:60)     在javax.servlet.http.HttpServlet.service(HttpServlet.java:648)at   javax.servlet.http.HttpServlet.service(HttpServlet.java:729)at at   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)     在   org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)     在   org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)     在   org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)     在   org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)     在   org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)     在   org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)     在   org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)     在   org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:617)     在   org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)     在   org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)     在   org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)     在   org.apache.coyote.AbstractProtocol $ AbstractConnectionHandler.process(AbstractProtocol.java:668)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.doRun(NioEndpoint.java:1521)     在   org.apache.tomcat.util.net.NioEndpoint $ SocketProcessor.run(NioEndpoint.java:1478)     在   java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)     在   java.util.concurrent.ThreadPoolExecutor中的$ Worker.run(ThreadPoolExecutor.java:617)     在   org.apache.tomcat.util.threads.TaskThread $ WrappingRunnable.run(TaskThread.java:61)     在java.lang.Thread.run(Thread.java:745)

2 个答案:

答案 0 :(得分:0)

您应该将contentType选项设置为false并且必须使用FormData类,contentType选项强制jQuery不添加Content-Type标头,否则边界字符串将丢失。

您还必须将processData标志设置为false,否则,jQuery将尝试将您的FormData转换为字符串,这将失败。

你的test.js文件必须像;

$(document).ready(function() {

    $('#btn').click(function() {
        event.preventDefault();

        var form = $('#myform')[0];
        var data = new FormData(form);

        $.ajax({
            type : "POST",
            enctype : 'multipart/form-data',
            url : '../FileUploadServlet2',
            data : data,
            processData : false,
            contentType : false,
            cache : false,
            success : function(responseText) {
                $('#ajaxGetUserServletResponse').text(responseText);
            }
        });
    }); 
});

在服务器端代码中,对于Servlet类,您需要添加@MultipartConfig

@WebServlet("/FileUploadServlet2")
@MultipartConfig
public class FileUploadServlet2 extends HttpServlet {
    ----------
}

答案 1 :(得分:0)

错误:无法解析上传请求:请求不包含 multipart/form-data 或 multipart/mixed 流,内容类型标头为 application/x-www-form-urlencoded;字符集=UTF-8

解决方案: 如果您使用带有 aui Request 的表单,请遵循以下解决方案:

const dateTimeLocalValue = $('#myTextbox').val();
const fakeUtcTime = new Date(`${dateTimeLocalValue}Z`);
const d = new Date(fakeUtcTime.getTime() + fakeUtcTime.getTimezoneOffset() * 60000);
console.log(d);