我正在学习 D3.js library 。如何使用 httpRequest 发送文件,如本示例中所述: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中,只需调用Javascript即可。
但这不是一个好的设计。 Servlet 在服务器端执行,Javascript 在客户端执行。如果您想从本地计算机上传文件,可以使用 Java 或 Javascript 的文件上传实用程序。从 Servlet 调用 Javascript 是不对的。
关于javascript - 通过http请求发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32547673/