稍微修改就能使用
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.*;
@RestController
@RequestMapping(value = "/uploadPDF")
public class URLUpload {
@RequestMapping("/upload")
public void export(String fileName,String path,HttpServletResponse httpServletResponse) {
final Logger logger = LoggerFactory.getLogger(URLUpload.class);
ServletOutputStream out = null;
InputStream inputStream = null;
try {
int indez = 0;
if (path == null){
logger.error("参数不正确,请检查参数!");
return;
}
indez = path.lastIndexOf(".");
String suffix = path.substring(indez);
logger.info("fileName = " + suffix);
String pdfName;
if (!fileName.trim().isEmpty()) {
pdfName = fileName + suffix;
logger.info("pdfName = " + pdfName);
} else {
pdfName = "公告" + suffix;
}
logger.info("IS DOWNLOADING:invPdfUrl=" + path);
URL url = new URL(null, path, new sun.net.www.protocol.https.Handler());
String proxyAddress = "**********";
int proxyPort = *****;
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyAddress, proxyPort));
HttpURLConnection conn = (HttpURLConnection) url.openConnection(proxy);
conn.setConnectTimeout(30 * 1000);
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
inputStream = conn.getInputStream();
httpServletResponse.setContentType("application/pdf");
httpServletResponse.setContentType("application/msword");
httpServletResponse.setContentType("application/powerpoint");
httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(pdfName, "UTF-8"));
httpServletResponse.setHeader("Cache-Control", "no-cache");
out = httpServletResponse.getOutputStream();
byte[] buffer = new byte[4096];
int len = 0;
while ((len = inputStream.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.flush();
logger.info("DOWNLOAD SUCCESS!");
} catch (IOException e) {
logger.error("DOWNLOAD FAILED!", e);
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}