将二进制数据发送到 servlet
我正在尝试将文件发送到 servlet。
function sendToServlet(){
var file = Components.classes["@mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3");
var boundary = "--------------" + (new Date).getTime();
var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance
// Send
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
req.open('POST', 'http://localhost:8080/app/server' , false);
var contentType = "multipart/form-data; boundary=" + boundary;
req.setRequestHeader("Content-Type", contentType);
req.send(stream);
}
JavaScript的来源: https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Sending_binary_data
但不起作用。
您好,这是使用的 serlevt 代码:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int size = 1024*20000;
long sizeFile = 0;
File savedFile = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(new Long("-1"));
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
try {
if (item.isFormField()) {
;
}else{
String itemName = item.getName();
int sizeName = itemName.length();
int end = itemName.indexOf('\n');
int start = itemName.lastIndexOf('\\');
itemName = itemName.substring(start + 1, sizeName-end-1);
savedFile = new File("C:\\Documents and Settings\\eric.silva\\Meus documentos\\"+itemName);
item.write(savedFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}//metodo
但是当我尝试发送文件时,servlet 不会创建发送的文件。 通过 javascript 进行 ento envira 的操作需要满足以下条件。 Mas o arquivo não é criado no lado do servidor。 Acredito que o código apresentado no site da MDN esteja 不完整。
当我尝试通过 javascript 发送时,请求被发送。但该文件不是在服务器端创建的。我认为 MDN 网站上显示的代码不完整。
I am trying send a file to a servlet.
function sendToServlet(){
var file = Components.classes["@mozilla.org/file/local;1"].
createInstance(Components.interfaces.nsILocalFile);
file.initWithPath("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3");
var boundary = "--------------" + (new Date).getTime();
var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]
.createInstance(Components.interfaces.nsIFileInputStream);
stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance
// Send
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]
.createInstance(Components.interfaces.nsIXMLHttpRequest);
req.open('POST', 'http://localhost:8080/app/server' , false);
var contentType = "multipart/form-data; boundary=" + boundary;
req.setRequestHeader("Content-Type", contentType);
req.send(stream);
}
The source of javascript:
https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Sending_binary_data
But does not work.
Hi, this the serlevt code used:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
int size = 1024*20000;
long sizeFile = 0;
File savedFile = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (!isMultipart) {
} else {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(new Long("-1"));
List items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
e.printStackTrace();
}
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
try {
if (item.isFormField()) {
;
}else{
String itemName = item.getName();
int sizeName = itemName.length();
int end = itemName.indexOf('\n');
int start = itemName.lastIndexOf('\\');
itemName = itemName.substring(start + 1, sizeName-end-1);
savedFile = new File("C:\\Documents and Settings\\eric.silva\\Meus documentos\\"+itemName);
item.write(savedFile);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}//metodo
But when i try to send a file the servlet dont create the file sent.
Quando eu tento enviar via javascript a requisição é enviada. Mas o arquivo não é criado no lado do servidor. Acredito que o código apresentado no site da MDN esteja incompleto.
When I try to send via javascript the request is sent. But the file is not created on the server side. I believe the code shown on the site of the MDN is incomplete.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请注意您使用的示例代码如何使用方法
PUT
发送数据 - 有效的multipart-formdata
请求需要有一些额外的标头,而不仅仅是文件本身。例如,您发送的文件应该有一个名称(通常是表单字段的名称)。您应该使用FormData
对象,它会自动生成一个有效的请求。您应该能够直接创建File
对象。类似的事情:请注意,仅从 Firefox 6 开始才支持创建这样的
File
对象。Note how the example code you are using is sending data with method
PUT
- validmultipart-formdata
request needs to have some additional headers, not only the file itself. For example, the file you are sending should have a name (normally the name of the form field). You should use aFormData
object instead, it will generate a valid request automatically. You should be able to create aFile
object directly. Something along these lines:Note that creating
File
objects like this is only supported starting with Firefox 6.问题更可能在于您如何尝试使用 servlet 获取上传的文件。作为低级实现,servlet 没有太多用于处理上传文件(多部分请求)的抽象。幸运的是,有一些库可以为您处理这些问题,例如 commons.FileUpload:
http://commons.apache .org/fileupload/using.html
只需像文档中所述那样使用 fileUpload 设置一个 servlet,然后使用具有文件上传输入的表单创建一个简单的 html 页面,并将其用作基本功能测试看看它是否有效,然后返回创建你自己的客户端。
The problem lies more likely in how you're trying to obtain the uploaded file with the servlet. Being a low level impelementation, the servlet doesn't have much of an abstraction for handling uploaded files (multi part requests). Luckily there are libraries who take care of that for you like commons.FileUpload:
http://commons.apache.org/fileupload/using.html
Just set up a servlet with fileUpload like it sais in the doc, then make a simple html page with a form that has a file upload input, and use that as a basic functional test to see that it works, then return to making your own client.