gpt4 book ai didi

java - 使用 GWT 中的 servlet 下载文件后表单操作没有休息?

转载 作者:行者123 更新时间:2023-12-02 03:39:05 25 4
gpt4 key购买 nike

我在GWT中开发了一个小应用程序,在进行一些操作后上传和下载文件,它工作正常,但加载对话框图像在文件下载后永远不会停止,请建议。

客户端代码

public class Firstmodule implements EntryPoint
{


public void onModuleLoad()
{

final PopupPanel popup = new PopupPanel(false, true); // Create a modal dialog box that will not auto-hide


final FileUpload fileUpload = new FileUpload();
final FormPanel form = new FormPanel();
VerticalPanel vPanel = new VerticalPanel();
Image img = new Image("download.png");
vPanel.add(img);

form.setMethod(FormPanel.METHOD_POST);
// The HTTP request is encoded in multipart format.
form.setEncoding(FormPanel.ENCODING_MULTIPART);

form.setTitle("Family_Common_Fet");
form.setAction(GWT.getHostPageBaseURL() + "FileUploadGreeting");
form.setWidget(vPanel);

fileUpload.setName("uploader");
vPanel.add(fileUpload);
vPanel.setSpacing(20);
Label maxUpload = new Label();
maxUpload.setText("Text input file header: Datasheet, Vendor Code");
vPanel.add(maxUpload);


final Button submit = new Button("Upload and Run");
vPanel.add(submit);
submit.addClickHandler(new ClickHandler() {

public void onClick(ClickEvent event)
{
String filename = fileUpload.getFilename();
if(!filename.endsWith(".txt"))
{
System.out.println(filename);
Window.alert("only *.txt files accepted");
return;
}
else if(filename.length() == 0)
{
Window.alert("Please Select Text File");
return;
}
else
{
// loading dialog image
popup.add(new Image("loading_animation1.gif"));
popup.setGlassEnabled(true); // Enable the glass panel
popup.center(); // Center the popup and make it visible

submit.setEnabled(false);
submit.setFocus(true);
form.submit();
}

}
});

// Add an event handler to the form.
form.addSubmitHandler(new FormPanel.SubmitHandler() {
public void onSubmit(SubmitEvent event)
{
// This event is fired just before the form is submitted. We can take
// this opportunity to perform validation.

}
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
public void onSubmitComplete(SubmitCompleteEvent event)
{

//trying to stop the loading dialodg
popup.setGlassEnabled(false);

submit.setEnabled(true);

form.reset();
}
});

DecoratorPanel decPanel = new DecoratorPanel();
decPanel.setWidget(form);

RootPanel.get("uploadContainer").add(decPanel);

}

servlet 代码

public class UploadFileHandler extends HttpServlet
{
private static final long serialVersionUID = 1L;

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{

System.out.println("Inside doPost");

// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload fileUpload = new ServletFileUpload(factory);
// sizeMax - The maximum allowed size, in bytes. The default value of -1 indicates, that there is no limit.
// 1048576 bytes = 1024 Kilobytes = 1 x 10 Megabyte
fileUpload.setSizeMax(10485760);
System.out.println(request.getRemoteAddr());

if(!ServletFileUpload.isMultipartContent(request))
{
try
{

throw new FileUploadException("error multipart request not found");
}catch(FileUploadException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}

try
{

List<FileItem> items = fileUpload.parseRequest(request);

if(items == null)
{
response.getWriter().write("File not correctly uploaded");
return;
}

Iterator<FileItem> iter = items.iterator();

String absofilepath = null;
String fileName = null;
String filepath = "temp//fileOutput_" + System.currentTimeMillis() + ".txt";
while(iter.hasNext())
{
FileItem item = (FileItem) iter.next();

////////////////////////////////////////////////
// http://commons.apache.org/fileupload/using.html
////////////////////////////////////////////////

// if (item.isFormField()) {
fileName = item.getName();
System.out.println("fileName is : " + fileName);
String typeMime = item.getContentType();
System.out.println("typeMime is : " + typeMime);
int sizeInBytes = (int) item.getSize();
System.out.println("Size in bytes is : " + sizeInBytes);
// byte[] file = item.get();

absofilepath = getServletContext().getRealPath(filepath);
item.write(new File(absofilepath));
// }

}

String request_ip = getClientIpAddr(request);
System.out.println("Request IP:" + request_ip);

String tempoutFile = "output//" + fileName + System.currentTimeMillis() + ".txt";
String absooutFile = getServletContext().getRealPath(tempoutFile);
System.out.println("ouput file : " + absooutFile);
//************ some other operations in code*******///


}catch(Exception e){
e.printStackTrace();
PrintWriter out = response.getWriter();
response.setHeader("Content-Type", "text/html");
out.println("an Error has occuredin Exporter.bat" + e);
out.flush();
out.close();
}


// ****************************Downlaod **********************************//
downloadFile(request, response, absooutFile);

/*when i sing hashed code below it's return error in console and didn't stop the loading dialog image */
// PrintWriter out = response.getWriter();
// response.setHeader("Content-Type", "text/html");
// out.println("Check output File");
// System.out.println("Upload Ok");
// out.flush();
// out.close();


}catch(SizeLimitExceededException e)
{
System.out.println("File size exceeds the limit : 10 MB!!");
PrintWriter out = response.getWriter();
response.setHeader("Content-Type", "text/html");
out.println("Maximum file size should not exceed 10MB!!");
out.flush();
out.close();
}catch(Exception e)
{
e.printStackTrace();
PrintWriter out = response.getWriter();
response.setHeader("Content-Type", "text/html");
out.println("an Error has occured");
out.flush();
out.close();
}

}

public static String getClientIpAddr(HttpServletRequest request)
{
String ip = request.getHeader("X-Forwarded-For");
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("HTTP_CLIENT_IP");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return ip;
}

private void downloadFile(HttpServletRequest req, HttpServletResponse resp, String filePath)
{
try
{
File f = new File(filePath);
int length = 0;
ServletOutputStream op = resp.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType(filePath);

resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
resp.setContentLength((int) f.length());
resp.setHeader("Content-Disposition", "attachment; filename=Fam_Com_Fet.txt");

DataInputStream in = new DataInputStream(new FileInputStream(f));
byte[] bbuf = new byte[in.available()];

while((in != null) && ((length = in.read(bbuf)) != -1))
{
op.write(bbuf, 0, length);
}

in.close();
op.flush();
op.close();

// f.delete();


}catch(IOException ioe)
{
ioe.printStackTrace();
}
}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}

谢谢

最佳答案

SubmitCompleteHandler 仅保证在服务器发回 HTML 时被调用,(请参阅 javadoc)它不适用于任意文件下载。

关于java - 使用 GWT 中的 servlet 下载文件后表单操作没有休息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37060085/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com