简体   繁体   中英

Send a file through an http request

I'm learning the D3.js library . How I can send a file with an httpRequest as described in this sample: chart ?

I have a local server tomcat within eclipse. Is it possible to use this?

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

And then catch it from:

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

By using Apache common jar, the sample code will be like this

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);
        }        
     }

Have a look at File Upload Servlet for complete code snippet

File upload with AJAX : AJAX file upload

EDIT

Calling javascript from servlet:

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

In this jsp, just call Javascript.

But this is not a good design. Servlet is executing at server and Javascript is executing at client end. If you want to upload file from your local machine, you can use File Upload Utility of Java Or Javascript. Calling Javascript from Servlet is not right thing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM