您的位置:首页 > 编程语言 > Java开发

javaWeb 上传下载(一)

2018-02-07 16:50 232 查看
form表单

<body>
<form id="subdata" action="${contextPath}/uploadFile" enctype="multipart/form-data" method="post" target="iUpload">
IP地址:<input type="text" name="recordIp"><br/>
机型版本:<input type="text" name="modelVersion"><br/>
软件版本:<input type="text" name="softVersion"><br/>
更新时间:<input type="text" name="updateTime"><br/>
报告下载:<input type="file" name="downfile"><br/>
报告地址:<input type="text" name="recordUrl"><br/>
备注描述:<input type="text" name="recordComment"><br/>
<input type="submit" value="提交">
</form>
<%--<iframe name="iUpload"  style="display:none"></iframe>--%>
</body>


message提示

%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<!DOCTYPE html>
<html lang="en">
<head>
<title>文件上传消息提示</title>
</head>
<body>
${message}
</body>
</html>


下载

public class DownloadServlet extends HttpServlet {

private String fileName;

public DownloadServlet(String fileName) {
this.fileName = fileName;
}

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String fileSaveRootPath = req.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//String fileSaveRootPath = req.getRealPath("/WEB-INF/upload");
String path = findFileSavePathByFileName(fileName, fileSaveRootPath);
File file = new File(path + "\\" + fileName);
System.out.println("文件路径" + file.getPath());

if (!file.exists()) {
req.setAttribute("message", "您要下载的资源已被删除!!");
//req.getRequestDispatcher("/message.jsp").forward(req, resp);
System.out.println("文件不存在");
return;
}
String message = "";
try {
FileInputStream in = new FileInputStream(path + "\\" + fileName);
OutputStream out = resp.getOutputStream();
resp.setContentType("application/force-download");
resp.setContentType("application/octet-stream");
resp.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//FileInputStream in = new FileInputStream("http://172.20.112.139:8080//test//downFile//"  + fileName);
byte buffer[] = new byte[1024];
int len = 0;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
out.flush();
}
in.close();
out.close();
} catch (Exception e) {
message = "文件下载失败";
e.printStackTrace();
}

}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}

public String findFileSavePathByFileName(String fileName, String fileSaveRootPath) {
String dir = fileSaveRootPath + "\\";
File file = new File(dir);
if (!file.exists()) {
file.mkdirs();
}
return dir;
}
}


上传

public class UploadServlet extends HttpServlet{

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

String savePath = req.getSession().getServletContext().getRealPath("/WEB-INF/upload");
//String savePath = req.getRealPath("/WEB-INF/upload");
System.out.println("保存的路径" + savePath);
File file = new File(savePath);
if (!file.exists() && !file.isDirectory()) {
System.out.println(savePath+"目录不存在,需要创建");
file.mkdir();
}
String message = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
if (!ServletFileUpload.isMultipartContent(req)) {
return;
}

try {
//获取表单数据
List<FileItem> list = upload.parseRequest(req);
for (FileItem item : list) {
//表单数据
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("UTF-8");
System.out.println(name + "=" + value);
} else {
//文件
String filename = item.getName();
System.out.println(filename);
if (filename == null || filename.trim().equals("")){
continue;
}

filename = filename.substring(filename.lastIndexOf("\\")+1);
InputStream in = item.getInputStream();

FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
byte buffer[] = new byte[8192];
int len = 0;
while ((len = in.read(buffer))!=-1){
out.write(buffer,0,len);
out.flush();
}
in.close();
out.close();
item.delete();
message="文件上传成功";
}
}
} catch (Exception e) {
message="文件上传失败";
e.printStackTrace();
}
req.setAttribute("message",message);
System.out.println(message);
}

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req,resp);
}
}


RequestMapping

@RequestMapping("/uploadFile")
public void uploadFile(HttpServletRequest req, HttpServletResponse resp, String recordIp, String modelVersion, String softVersion,
String updateTime, String recordUrl, String recordComment)
throws ServletException, IOException {
log.debug("进入uploadFile");

UploadServlet uploadServlet = new UploadServlet();
uploadServlet.doPost(req, resp);
//return "bspreport/message";
}

@RequestMapping("/loadFile")
public void loadFile(@Param("id") Integer id, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//服务器 host地址+ "/WEB-INF/upload/123.txt"(recordUrl 格式);
//完整下载地址 "/WEB-INF/upload/123.txt";
SpotRecordBO spotRecordBO = spotRecordService.getBySpotRecordId(id);
String recordUrl = spotRecordBO.getRecordUrl();
String fileName = recordUrl.substring(recordUrl.lastIndexOf("/") + 1);
//fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
DownloadServlet downloadServlet = new DownloadServlet(fileName);
downloadServlet.doPost(req, resp);
req.setAttribute("message", "文件下载成功");
//return "bspreport/message";
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息