一、如何实现文件上传
*上传*
1.文件上传,创建项目开发
2.创建UploadServlet类主要用于获取表单及其上传文件的信息
3.index.jsp页面的代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>文件上传</title>
</head>
<body>
<div align="center">
<form action="UploadServlet" enctype="multipart/form-data" method="post">
名称:<input name="name" /> <br>
上传文件:<input name="img" type="file"/><br>
<input type="submit" value="提交" />
<input type="reset" value="重置" />
</form>
</div>
</body>
</html>
二、文件上传的相关API
message.jsp代码:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>上传文件成功</title>
</head>
<body>
<h1 align="center">上传文件成功!</h1>
</body>
</html>
UploadServlet代码:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
DiskFileItemFactory sf= new DiskFileItemFactory();//实例化磁盘被文件列表工厂
String path = request.getRealPath("/upload");//得到上传文件的存放目录
sf.setRepository(new File(path));//设置文件存放目录
sf.setSizeThreshold(1024*1024);//设置文件上传小于1M放在内存中
String rename = "";//文件新生成的文件名
String fileName = "";//文件原名称
String name = "";//普通field字段
//从工厂得到servletupload文件上传类
ServletFileUpload sfu = new ServletFileUpload(sf);
try {
List<FileItem> lst = sfu.parseRequest(request);//得到request中所有的元素
for (FileItem fileItem : lst) {
if(fileItem.isFormField()){
if("name".equals(fileItem.getFieldName())){
name = fileItem.getString("UTF-8");
}
}else{
//获得文件名称
fileName = fileItem.getName();
fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
String houzhui = fileName.substring(fileName.lastIndexOf("."));
rename = UUID.randomUUID()+houzhui;
fileItem.write(new File(path, rename));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
response.sendRedirect("message.jsp");
out.flush();
out.close();
}
}
web的配置文件:
三、实现文件上传
上传页面:
文件上传成功:
四、实现文件下载
前端实现下载代码:
<td>
<button type="button" id="btn_query" class="btn btn-primary pull-right"
onclick="download('${credit.score_card_uuid}')">下载
</button>
</td>
var excel_param;
excel_param = {
'start_time' : $("#start_time").val(),
'end_time' : $("#end_time").val(),
'order_uuids' : order_uuids
};
function download() {
postDownLoadFile({
url : '/ces/ces.do',
data : excel_param,
method : 'post'
});
$('#excel_modal').modal('hide');
}
var postDownLoadFile = function(options) {
var config = $.extend(true, {
method : 'post'
}, options);
var $iframe = $('<iframe id="down-file-iframe" />');
var $form = $('<form target="down-file-iframe" method="' + config.method + '" />');
$form.attr('action', config.url);
for ( var key in config.data) {
$form
.append('<input type="hidden" name="' + key + '" value="' + config.data[key] + '" />');
}
$iframe.append($form);
$(document.body).append($iframe);
$form[0].submit();
$iframe.remove();
}
后端的实现代码:
@RestController
@RequestMapping("/file")
public class DownloadController1 {
//业务上需要的参数可以如param1 传递
@RequestMapping(value = "/download")
public Map<String, Object> download(HttpServletRequest request, HttpServletResponse response,String param1,String param2 ) throws Exception {
String realName = "第一节(2).zip"; //文件在浏览器的显示位置
String downLoadPath = ""; //这个参数表示文件在服务器的存储路径
String contentType = "application/octet-stream";
try {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
long fileLength = new File(downLoadPath).length();
response.setContentType(contentType);
response.setHeader("Content-disposition",
"attachment; filename=" + new String(realName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
bis.close();
bos.close();
return ResultUtil.put(ConstantUtil.REQUEST_SUCCESS, "", "");
} catch (Exception e) {
return ResultUtil.put(ConstantUtil.REQUEST_FAIL, "", "");
}
}
}
运行结果: