gpt4 book ai didi

java - 如何在 Java 中下载 .msi 文件

转载 作者:行者123 更新时间:2023-12-01 15:18:47 24 4
gpt4 key购买 nike

我想使用 Java 下载 .msi 文件。我尝试使用以下代码下载文件

PrintWriter out = null;
FileInputStream fileToDownload = null;
BufferedReader bufferedReader = null;
try {
out = response.getWriter();
fileToDownload = new FileInputStream(DOWNLOAD_DIRECTORY + FILE_NAME);
bufferedReader = new BufferedReader(new InputStreamReader(fileToDownload));

//response.setContentType("application/text");
//response.setContentType("application/x-msi");
//response.setContentType("application/msi");
//response.setContentType("octet-stream");
response.setContentType("application/octet-stream");
//response.setContentType("application/x-7z-compressed");
//response.setContentType("application/zip");
response.setHeader("Content-disposition","attachment; filename=" +FILE_NAME );
response.setContentLength(fileToDownload.available());

System.out.println("\n now file download is starting");
String NextLine = "";
while((NextLine = bufferedReader.readLine()) != null){
out.println(NextLine);
}
out.flush();

} catch (IOException e) {
out.write("<center><h2>The Installer is not Available on Server</h2></center>");
System.out.println("\n Got Exception while getting the input Stream from the file==>"+e);
log.error("Error::", e);
}
finally{
if(null != bufferedReader){
try {
bufferedReader.close();
} catch (IOException e) {
System.out.println("\n Error in closing buffer Reader==>"+e);
log.error("Error::", e);
}
}// End of if

if(null != fileToDownload){
try {
fileToDownload.close();
} catch (IOException e) {
System.out.println("\n Error in closing input stream==>"+e);
log.error("Error::", e);
}
}// End of if
}// End of finally

最佳答案

在这种情况下,您无法使用 readline() 读取二进制(msi)文件。您的代码完全错误,将无法工作。这是一个简单的函数,可以让您做您想做的事情。

    private void doDownload( HttpServletRequest req, HttpServletResponse resp,String filename, String original_filename )throws IOException
{
File f = new File(filename);
int length = 0;
ServletOutputStream op = resp.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType( filename );
resp.setContentType( (mimetype != null) ? mimetype : "application/octet-stream" );
resp.setContentLength( (int)f.length() );
resp.setHeader( "Content-Disposition", "attachment; filename=\"" + original_filename + "\"" );
byte[] bbuf = new byte[BUFSIZE];
DataInputStream in = new DataInputStream(new FileInputStream(f));
while ((in != null) && ((length = in.read(bbuf)) != -1)){
op.write(bbuf,0,length);
}
in.close();
op.flush();
op.close();
}

servlet 中创建 doDownload() 函数,并将所需参数从 doGetdoPost 传递给该函数或您喜欢的任何有效位置。

参数:

  • @param req 请求

  • @param resp 响应

  • @param filename 您要下载的文件的名称。

  • @param original_filename 浏览器应接收的名称。

关于java - 如何在 Java 中下载 .msi 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11259144/

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