java 文件下载后打开时提示文件损坏

以下的经测试都是正确的。

出现损坏的原因:

https://www.jianshu.com/p/f4016e2e1158

并不是每次都能读到1024个字节,所有用readTmp作为每次读取数据的长度,否则会出现文件损坏的错误

本地文件下载:

public static void downloadLocal(HttpServletResponse response,String path,String fileName){
		FileInputStream fileIn = null;
		ServletOutputStream out = null;
		try {
			//String fileName = new String(fileNameString.getBytes("ISO8859-1"), "UTF-8");
			response.setContentType("application/octet-stream");
			// URLEncoder.encode(fileNameString, "UTF-8") 下载文件名为中文的,文件名需要经过url编码
			response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
			File file;
			String filePathString = path + fileName;
			file = new File(filePathString);
			fileIn = new FileInputStream(file);
			out = response.getOutputStream();

			byte[] outputByte = new byte[1024];
			int readTmp = 0;
			while ((readTmp = fileIn.read(outputByte)) != -1) {
				out.write(outputByte, 0, readTmp); //并不是每次都能读到1024个字节,所有用readTmp作为每次读取数据的长度,否则会出现文件损坏的错误
			}
		}
		catch (Exception e) {
			//log.error(e.getMessage());
			e.printStackTrace();
		}
		finally {
			try {
				fileIn.close();
				out.flush();
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

网络文件下载

https://blog.csdn.net/xiansu5452/article/details/79485388

/**
     *      * TODO 下载文件到本地
     *      *  
     *      * @date Sep 11, 2015 11:45:31 AM
     *      * @param fileUrl 远程地址
     *      * @param fileLocal 本地路径
     *      * @throws Exception 
     *      
     */
    public static boolean downloadFile(String fileUrl, String fileLocal) throws Exception {
        boolean flag = false;
        URL url = new URL(fileUrl);
        HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
        urlCon.setConnectTimeout(6000);
        urlCon.setReadTimeout(6000);
        int code = urlCon.getResponseCode();
        if (code != HttpURLConnection.HTTP_OK) {
            throw new Exception("文件读取失败");
        }
        //读文件流
        DataInputStream in = new DataInputStream(urlCon.getInputStream());
        DataOutputStream out = new DataOutputStream(new FileOutputStream(fileLocal));
        byte[] buffer = new byte[2048];
        int count = 0;
        while ((count = in.read(buffer)) > 0) {
            out.write(buffer, 0, count);
        }
        try {
            if (out != null) {
                out.close();
            }
            if (in != null) {
                in.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        flag = true;
        return flag;
    }

猜你喜欢

转载自blog.csdn.net/xinyuebaihe/article/details/88249561
今日推荐