解决如何从服务器上下载图片或文件到本地的方案代码
1.前台html的代码
<label class="layui-form-label mingzi">下载内容</label>
<input type="text" name="xiazaiId" class="layui-input kuan">
<button type="button" class="layui-btn xia" >立即下载</button>
2.前台js的代码
$(document).on("click",".xia",function(){
var xiazaiId= $("input[name='xiazaiId']").val();
location.href="${pageContext.request.contextPath }/addxiazai.json?xiazaiId="+xiazaiId;
})
3.后台相应的代码
@ResponseBody
@RequestMapping(value="/addxiazai")
public void addEvaluate(HttpServletRequest request,HttpServletResponse response)
{
String xiazaiId=request.getParameter("xiazaiId");
System.out.println("xiazai========="+xiazaiId);
xiazai.download0(xiazaiId,"GET",response);
}
public static void download0(String fileName, String method,HttpServletResponse response) {
String contextPath = "http://www.pwxvr.com/dangjian/statics/uploadfiles1/"+fileName;
System.out.println("contextPath======"+contextPath);
InputStream inputStream = null;
OutputStream bufferOut = null;
HttpURLConnection conn = null;
try {
URL url = new URL(contextPath);
URLConnection urlConnection = url.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
httpURLConnection.setConnectTimeout(1000*5);
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setRequestProperty("Charset", "UTF-8");
httpURLConnection.connect();
int contentLength = httpURLConnection.getContentLength();
inputStream=httpURLConnection.getInputStream();
String fileFullName = contextPath.substring(contextPath.lastIndexOf("/")).substring(1);
response.reset();
response.setContentLength(contentLength);
response.setContentType("application/x-jpg");
response.addHeader("Content-Disposition", "attachment; filename=" +fileFullName);
bufferOut = response.getOutputStream();
byte[] buffer = new byte[1024];
int len=0;
while ((len=inputStream.read(buffer))!=-1){
bufferOut.write(buffer, 0, len);
}
System.out.println("下载成功啦————————————————————————————————");
}
catch (Throwable e) {
if (e instanceof ClientAbortException) {
System.out.println("用户取消下载!");
} else {
System.out.println("下载文件失败....!");
}
e.printStackTrace();
} finally {
try {
if (bufferOut != null) {
bufferOut.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
4.谢谢各位的浏览
工作几年,略有心得,然很少整理成文,平常工作中浏览了不少道友的好文章,受益良多。
顾也开始写一些文章, 希望能与各位道友分享进步 !!!!
如果有用,欢迎各位点赞评论,若有不足,亦可指正!!!