java webapp 几种文件上传和下载方式
下载方式:
第一种:
<a href="文件地址",download="文件名">a>
1
测试pc端chorme,safari,ie11,edge,可用,,移动端,,ios可直接开打pdf,word等文件,android上只有qq浏览器可直接查看,其他均要下载.
第二种:
springmvc实现
@RequestMapping("/download")
public String download(@RequestParam String fileName, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
try {
//Content-Disposition文件名中文编码问题
String new_filename = URLEncoder.encode(fileName, "UTF8");
// 如果没有UA,则默认使用IE的方式进行编码,因为毕竟IE还是占多数的
String rtn = "filename=\"" + new_filename + "\"";
String userAgent = request.getHeader("user-agent");
if (userAgent != null)
{
userAgent = userAgent.toLowerCase();
// IE浏览器,只能采用URLEncoder编码
if (userAgent.indexOf("msie") != -1)
{
rtn = "filename=\"" + new_filename + "\"";
}
// Opera浏览器只能采用filename*
else if (userAgent.indexOf("opera") != -1)
{
rtn = "filename*=UTF-8''" + new_filename;
}
// Safari浏览器,只能采用ISO编码的中文输出
else if (userAgent.indexOf("safari") != -1 )
{
rtn = "filename=\"" + new String(fileName.getBytes("UTF-8"),"ISO8859-1") + "\"";
}
// Chrome浏览器,只能采用MimeUtility编码或ISO编码的中文输出
else if (userAgent.indexOf("applewebkit") != -1 )
{
new_filename = MimeUtility.encodeText(fileName, "UTF8", "B");
rtn = "filename=\"" + new_filename + "\"";
}
// FireFox浏览器,可以使用MimeUtility或filename*或ISO编码的中文输出
else if (userAgent.indexOf("mozilla") != -1)
{
rtn = "filename*=UTF-8''" + new_filename;
}
}
response.setHeader("Content-Disposition", "attachment;"+rtn);
String path = request.getSession().getServletContext().getRealPath("/") + "upload/inform/" ;
System.out.println(fileName);
InputStream inputStream = new FileInputStream(new File(path
+ File.separator + fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// 返回值要注意,要不然就出现下面这句错误!
//java+getOutputStream() has already been called for this response
return null;
}
html代码
但是这种方法在ios浏览器不能直接打开pdf,word等文件,需要下载,andoird上,各浏览器也不行.
上传方式
springmvc MultipartFile方式.
java代码
@RequestMapping(value="/fileUpload",method= RequestMethod.POST)
public String fileUpload(HttpServletRequest request,@RequestParam("file") MultipartFile file,@ModelAttribute Inform inform) throws IOException {
try {
int id = service.insertInform(inform);
if (!file.isEmpty()) {
// 文件保存路径
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/inform/"
+file.getOriginalFilename();
// 转存文件
file.transferTo(new File(filePath));
}
} catch (Exception e) {
e.printStackTrace();
return "uploadErro";
}
// 重定向
return "uploadSuccess";
}
*这里的文件作为附件功能上传
html代码*
可与model一起上传..
这是目前最简单的方法了,还有其他方法我看都比较复杂,写下这个记录,