第一步,写上传样式 <input type="button" value="选择文件" οnclick="uploadApply()"> <div> <ul style="list-style:none;" id="applyList"></ul> </div> <input type="file" style="display: none;" name="file" id="applyFiles" multiple="multiple" οnchange="showApply();">
第二步,写js方法
//点击选择文件,触发file的click事件
function uploadApply(){
$("#applyFiles").click();
}
/** 选择文件后,文件名的回显,并且添加文件到formData中 */ function showApply() { debugger $("#applyList").html("");//清空ul列表 var theFile = document.getElementById("applyFiles");//获取文件 var temp = ""//存放文件名 for (var i = 0; i < theFile.files.length; i++) {//遍历文件 formData.append("applyFiles", theFile.files[i])//放入文件到formdata中 temp += theFile.files[i].name + ";"; //构建li标签,插入到ul列表 var li = $("<li></li>"); li.html(theFile.files[i].name) $("#applyList").append(li); console.log(temp); } }
//保存文件到后台
function saveDeal() {
Base.showMask();
formData.append("xxx", "1")//放入键值对数据
$.ajax(
{
url: "reviewController!save.do",
type: "post",
data: formData,
// 告诉jQuery不要去处理发送的数据
processData: false,
// 告诉jQuery不要去设置Content-Type请求头
contentType: false,
success: function (res) {
res = JSON.parse(res);
if (res.success) {
//成功消息
$("#dealList").html("");
$("#applyList").html("");
formData=new FormData();//初始化formData
getFileList();
} else {
//错误消息
}
}
}
)
}
//下载文件 function downloadFile() { window.location.href='reviewController!getImage.do?fileUrl='+fileUrl; }
第三步,java后端代码
1.下载代码
/** * 根据附件ID查看附件图片 * * @return */ @RequestMapping("reviewController!getImage.do") public String getImage(HttpServletRequest request, HttpServletResponse response) throws IOException { response.addHeader("Content-Disposition", "attachment;filename=" + new String("d786891a4907f0f6bbdb1006a3e8cfed.jpg".getBytes("utf-8"), "ISO-8859-1")); //使用一个网络图片地址来下载 String url = "http://file06.16sucai.com/2016/0430/d786891a4907f0f6bbdb1006a3e8cfed.jpg"; InputStream inputStream = null; OutputStream outputStream = null; try { URL u = new URL(url); URLConnection conn = u.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 5.0;Windows NT;DigExt)"); inputStream = conn.getInputStream(); outputStream = response.getOutputStream(); byte[] bytes = new byte[2048]; int len; while ((len = inputStream.read(bytes)) != -1) { outputStream.write(bytes, 0, len); } } catch (Exception e) { logger.error(e.getMessage(), e); } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } return null; }