0
点赞
收藏
分享

微信扫一扫

Java Spring MVC 框架文件的上传下载以及文件显示

1:在SpringMVC框架的项目中引入文件上传所需的jar包

2.在WEB-INF/views/upload目录下新建上传文件页面创一个jsp文件,命名“file.jsp”。放入如下代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link href="../../css/bootstrap.min.css" rel="stylesheet">  
<script type="text/javascript"
	src="${pageContext.request.contextPath}/statics/scripts/jquery-3.6.0.min.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/statics/scripts/jquery-form.js"></script>
<title>注册界面</title>
<script type="text/javascript">
function ajaxUpload(){
	//获取表单数据,并添加到FormData中
	let myfile=$("#myfile")[0].files[0];
	let description=$("#description").val();
	let formData=new FormData();
	formData.append("myfile",myfile);
	formData.append("description",description);
	//发送AJAX请求
	$.ajax({
		//定义请求地址
		url:"${pageContext.request.contextPath}/doRemoteUpload",
		//定义请求类型
		type:"post",
		//定义请求参数(使用js对象)
		data:formData,
		//告诉jQuery不要去处理发送的数据,我们已经通过FormData处理了
		processData:false, 
		contentType: false,
		//定义服务器响应的数据格式为json
		dataType:"json",
		//成功响应的结果,data就是服务器返回的json对象
		success:function(data){
			alert(data.msg);
			if(data.flag=="1"){
				$("#img").attr("src","${pageContext.request.contextPath}/doUpload/"+data.content);
			}
		}
	}); }
</script>
</head>
<body>
	<form id="fileForm" action="${pageContext.request.contextPath}/doUpload" method="post" enctype="multipart/form-data">
	<h1>用户注册</h1>
	<tr>
	<td>
	选择头像:<input type="file" id="myfile" name="myfile"></td></tr>	
	<TABLE border="1">	
	<tr>
	<td>用户名:</td>
	<td><input type="text" name="username"></td>
	</tr>	
	<tr>
	<td> 密码:</td>
	<td><input type="password" name="password"></td>
	</tr>
	<tr>
	<td> 性别:</td>	
	<td><input type="text" name="sex"></td>
	</tr>
	<tr>
	<td> 年龄:</td>
	<td><input type="text" name="age"></td>
	</tr>
	<tr>
	<td> 出生日期:</td>
	<td><input type="date" name="birthDay"></td>
	</tr>
	<tr>
	<td><img alt="" id="img" src=""></td>
	</tr>
	<tr>
	<td> <input type=submit  value="注册"></td>
	<td><input type="reset" value="重  置"></td>
	</tr>	
	</TABLE>
</body>
</html>

3.在注册上传成功的页面(register_succ.jsp)中写:

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>

</head>
<body>
<form id="fileForm"
		action="${pageContext.request.contextPath}/doUpload" method="post"
		enctype="multipart/form-data">
	<fieldset>
		<legend>文件上传成功!</legend>
		服务器文件名:${filename}<br> 文件描述:${description}<br>
		<a href="${pageContext.request.contextPath}/uploadfiles/${filename}">
			点击下载文件【超链接方式】
		</a>
		<br>
		<a href="${pageContext.request.contextPath}/download/${filename}">		
			点击下载文件【下载对话框方式】			
		</a>
		
		<h1>注册成功</h1>
	<h1> 姓名:${param.username}</h1>
	<h1>年龄:${param.age}</h1>
	<h1>性别:${param.sex}</h1>
	<h1>生日:${param.birthDay}</h1> 
	<h1>头像<img alt ="" id="img" src = "${pageContext.request.contextPath}/uploadfiles/${filename}"></h1>//显示头像,一定要写,不然文件显示不出来

	</fieldset>

</form>
</body>
</html>

3.创一个 UploadController(这里要注意拟采用的是什么方式,我就用的doRemoteUpload,在register.jsp上面)

package controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;

import entity.MsgResult;

@Controller
public class UploadController {
	@RequestMapping("/upload")
	public String upload() {
		return "upload/file";
	}

	@RequestMapping("/doUpload")
	public String doUpload(MultipartFile myfile, String description, HttpServletRequest request)
			throws IllegalStateException, IOException {
		// 指定文件上传到服务器的位置(/uploadfiles)
		String realPath = request.getServletContext().getRealPath("uploadfiles");
		System.out.println(realPath);
		// 为上传到服务器的文件取名,使用UUID防止文件名重复
		String filename = UUID.randomUUID().toString() + "-" + myfile.getOriginalFilename();
		// 将文件名和描述传递到成功页显示
		request.setAttribute("filename", filename);
		request.setAttribute("description", description);

		File targetFile = new File(realPath, filename);
		// 判断路径中的文件夹是否存在,如果不存在,则创建
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 文件传输
		myfile.transferTo(targetFile);

		return "upload/upload_succ";
	}

	@RequestMapping("/doRemoteUpload")
	@ResponseBody
	public MsgResult doRemoteUpload(MultipartFile myfile, String description, HttpServletRequest request) {

		String path = "http://localhost:8088/uploadfiles/";

		// 为上传到服务器的文件取名,使用UUID防止文件名重复
		String filename = UUID.randomUUID().toString() + "-" + myfile.getOriginalFilename();
		MsgResult result = new MsgResult();
		try {
			// 使用Jersey客户端上传文件
			Client client = Client.create();
			WebResource webResource = client.resource(path + "/" + URLEncoder.encode(filename, "utf-8"));
			webResource.put(myfile.getBytes());
			result.setFlag(1);
			result.setMsg("文件上传成功");
			result.setContent(path + filename);
		} catch (Exception ex) {
			result.setFlag(1);
			result.setMsg("文件上传失败");
		}
		return result;
	}

	@RequestMapping("/download/{filename}")
	public ResponseEntity<byte[]> download(@PathVariable String filename, HttpServletRequest request)
			throws IOException {
		// 获取要下载文件字节流
		ServletContext servletContext = request.getServletContext();
		InputStream in = servletContext.getResourceAsStream("uploadfiles/" + filename);
		// 设置响应内容:将文件转换为字节数组
		byte[] body = new byte[in.available()];
		in.read(body);
		// 设置响应头,激活下载框
		HttpHeaders headers = new HttpHeaders();
		headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
		// 设置响应状态为200
		HttpStatus statusCode = HttpStatus.OK;
		// 根据页面内容、页面头、页面状态创建并跳转到该页面(实际返回的是下载文件数据)
		ResponseEntity<byte[]> response = new ResponseEntity<byte[]>(body, headers, statusCode);
		return response;
	}

	@RequestMapping("/doAjaxUpload")
	@ResponseBody
	public MsgResult doAjaxUpload(MultipartFile myfile, String description, HttpServletRequest request) {
		// 文件上传到服务器的位置(/uploadfiles)
		String realPath = request.getServletContext().getRealPath("uploadfiles");
		System.out.println(realPath);
		// 为上传到服务器的文件取名,使用UUID防止文件名重复
		String filename = UUID.randomUUID().toString() + "-" + myfile.getOriginalFilename();
		File targetFile = new File(realPath, filename);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		MsgResult result = new MsgResult();
		try {
			myfile.transferTo(targetFile);
			result.setFlag(1);
			result.setMsg("文件上传成功");
			result.setContent(filename);
		} catch (Exception ex) {
			result.setFlag(1);
			result.setMsg("文件上传失败");
		}

		return result;
	}

}

4.注册页面显示(我的样式很丑,急用了一个css,大家引用的时候要注意层级目录。当前‘.’;上一级"..";上两级“../../”)

 

5.运行结果:

 

 

举报

相关推荐

0 条评论