通过http请求发送文件

Send a file through an http request

我正在学习 D3.js library. How I can send a file with an httpRequest as described in this sample: chart?

我在 eclipse 中有一个本地服务器 tomcat。这个可以用吗?

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
     //send file from here
}

然后从以下位置捕获它:

d3.tsv("data.tsv", function(error, data) {
    if (error) throw error;

使用Apache common jar,示例代码如下

if(ServletFileUpload.isMultipartContent(request)){
   try {
            List<FileItem> multiparts = new ServletFileUpload(
                                     new DiskFileItemFactory()).parseRequest(request);

            for(FileItem item : multiparts){
                if(!item.isFormField()){
                    String name = new File(item.getName()).getName();
                    item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                }
            }
           //File uploaded successfully
           request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
           request.setAttribute("message", "File Upload Failed due to " + ex);
        }        
     }

查看 File Upload Servlet 以获得完整的代码片段

文件上传 AJAX :AJAX file upload

编辑

从 servlet 调用 javascript:

   request.getRequestDispatcher("/some.jsp").forward(request,response)

在此jsp中,只需调用Java脚本。

但这不是一个好的设计。 Servlet 在服务器端执行,Javascript 在客户端执行。如果您想从本地计算机上传文件,可以使用 Java 或 Java 脚本的文件上传实用程序。从 Servlet 调用 Javascript 是不对的。