我希望该客户在他的计算机上搜索一个 txt 文件,然后将其导入。这是一个包含此站点首选项的文件。我已经用 FileUpload 完成了,但我有一个错误:
javax.servlet.ServletException: Content-Type was 'multipart/form-data; boundary=---------------------------14895149261880284533914609527'. Expected 'text/x-gwt-rpc'.
我到处搜索,什么都没有……还有其他方法可以导入吗?或者我做错了什么。这是我的代码:
final DialogBox dialogBox = new DialogBox();
dialogBox.setAnimationEnabled(true);
dialogBox.setVisible(true);
dialogBox.center();
dialogBox.setText("Load settings file");
final FormPanel form = new FormPanel();
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
form.addStyleName("loadSettingsfile");
form.setWidth("275px");
form.setAction(GWT.getModuleBaseURL()+"fileUpload");
VerticalPanel holder = new VerticalPanel();
final FileUpload upload = new FileUpload();
upload.setName("upload");
holder.add(upload);
holder.add(new HTML("<hr />"));
holder.setHorizontalAlignment(HasAlignment.ALIGN_RIGHT);
HorizontalPanel hrPan = new HorizontalPanel();
Button submitButton = new Button("Load settings");
Button cancelButton = new Button("Cancel");
hrPan.add(cancelButton);
hrPan.add(submitButton);
holder.add(hrPan);
form.add(holder);
submitButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
form.submit();
}
});
cancelButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
dialogBox.hide();
}
});
form.addSubmitCompleteHandler(new SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event) {
//Window.alert(event.getResults());
dialogBox.hide();
}
});
form.addSubmitHandler(new SubmitHandler() {
public void onSubmit(SubmitEvent event) {
}
});
dialogBox.setWidget(form);
和小服务程序:
public class FileUpload extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();
response.setContentType("text/x-gwt-rpc");
response.addHeader("Path", request.getPathInfo());
try{
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
InputStream stream = item.openStream();
// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
int maxFileSize = 10*(1024*1024); //10 megs max
if (out.size() > maxFileSize) {
throw new RuntimeException("File is > than " + maxFileSize);
}
}
}
catch(Exception e){
throw new RuntimeException(e);
}
}