URL下载和服务器下载是不同的,
如果是从服务区上下载,需要提供服务器的文件路径来创建输入流
FileInputStream fileInputStream = new FileInputStream(new File("\User\User.pdf"));
如果是从URL上面下载,则需要提供域名访问地址,通过构建url作为输入流
//构造URL
URL url = new URL("https://downloads.mysql.com/docs/ndb-internals-en.a4.pdf");
URLConnection con = url.openConnection();
con.setConnectTimeout(20 * 1000);
InputStream inputStream = con.getInputStream();
代码示例
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
@Controller
public class Download {
@RequestMapping("/downloadFile")
@ResponseBody
public void downloadFile(HttpServletResponse response) throws IOException {
//构造URL
URL url = new URL("https://downloads.mysql.com/docs/ndb-internals-en.a4.pdf");
URLConnection con = url.openConnection();
con.setConnectTimeout(20 * 1000);
//
// FileInputStream fileInputStream = new FileInputStream(new File("d:\\XXX"));
try {
// 通过输入流读取文件内容
InputStream inputStream = con.getInputStream();
// 指定目的路径,获取到输出流
File out = new File("D:\\test1");
if (!out.exists()) {
out.mkdirs();
}
OutputStream outputStream = new FileOutputStream(out.getPath()+"\\"+"1.pdf");
int len = 0;
byte[] bytes = new byte[1024];
while ((len = inputStream.read(bytes)) != -1){
// 通过输出流,下载到本地
outputStream.write(bytes,0,len);
// // 刷新
// outputStream.flush();
}
// 5、关闭资源
outputStream.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1万+

被折叠的 条评论
为什么被折叠?



