简单的把文件转成流保存的上传下载方法:
常量定义:
1 2 | private static final String filePath = "D:/a_photo/" ; //本地测试 // private static final String filePath = "/var/";//服务器测试 |
注意:对应的 controller 类,注解不能用:@RestController ,而是使用 @Controller
上传方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | /** * 上传文件 * @author Mongo * @param file * @param request * @param response */ @RequestMapping (value = "/fileUpload" , method = RequestMethod.POST, produces = "text/html; charset=UTF-8" ) public void fileUpload(MultipartFile file, HttpServletRequest request,HttpServletResponse response) { Map<String, Object> data = new HashMap<String, Object>(); data.put( "msg" , "fail" ); data.put( "data" , null ); try { if (file.isEmpty()) { logger.info( "==== 上传的文件为空 ====" ); data.put( "msg" , "上传的文件为空" ); response.setContentType( "text/html; charset=UTF-8" ); JsonUtils.writeValue(response.getWriter(), data); return ; } String fileName = file.getOriginalFilename(); // 文件名 String suffixName = fileName.substring(fileName.lastIndexOf( "." )); // 后缀名 String uuid = UUID.randomUUID().toString().replace( "-" , "" ); fileName = uuid + suffixName; // 新文件名 File nameAndPath = new File(filePath + fileName);<br> dest.setWritable( true , false ); //linux下需要赋予权限才能上传成功 if (!nameAndPath.getParentFile().exists()) { nameAndPath.getParentFile().mkdirs(); } file.transferTo(nameAndPath); logger.info( "==== 上传成功 ====" ); data.put( "msg" , "success" ); data.put( "data" , fileName); //往浏览器输出成功与否结果 response.setContentType( "text/html; charset=UTF-8" ); JsonUtils.writeValue(response.getWriter(), data); } catch (IOException e) { e.printStackTrace(); logger.error( "==== 上传失败异常 ====" ,e); } return ; } |
下载方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | /** * 下载文件url * @author Mongo * @param request * @param response * @param filename */ @RequestMapping (value = "/fileDownland" , method = RequestMethod.GET, produces = "text/html; charset=UTF-8" ) public void fileDownland(HttpServletRequest request, HttpServletResponse response) { String fileName = request.getParameter( "fileName" ); String path = filePath + fileName; logger.info( "== 下载链接为: == " +path); File file = new File(path); OutputStream out = null ; FileInputStream in = null ; try { // 文件存在才下载 if (file.exists()) { // 1.读取要下载的内容 in = new FileInputStream(file); // 2. 告诉浏览器下载的方式以及一些设置 // 解决文件名乱码问题,获取浏览器类型,转换对应文件名编码格式,IE要求文件名必须是utf-8, firefo要求是iso-8859-1编码 String agent = request.getHeader( "user-agent" ); if (agent.contains( "FireFox" )) { fileName = new String(fileName.getBytes( "UTF-8" ), "iso-8859-1" ); } else { fileName = URLEncoder.encode(fileName, "UTF-8" ); } // 设置下载文件的mineType,告诉浏览器下载文件类型(下面这两句可以不要) //String mineType = request.getServletContext().getMimeType(fileName); //response.setContentType(mineType); // 设置一个响应头,无论是否被浏览器解析,都下载 response.setHeader( "Content-disposition" , "attachment; filename=" + fileName); // 将要下载的文件内容通过输出流写到浏览器 out = response.getOutputStream(); int len = 0 ; byte [] buffer = new byte [ 1024 ]; while ((len = in.read(buffer)) > 0 ) { out.write(buffer, 0 , len); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (out != null ) { out.close(); } if (in != null ) { in.close(); } } catch (Exception e2) { // TODO: handle exception } } } |
对应的工具类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | private static ObjectMapper mapper = new ObjectMapper();<br> /** * 将对象转换为JSON流 * * @param writer * writer * @param value * 对象 */ public static void writeValue(Writer writer, Object value) { try { mapper.writeValue(writer, value); } catch (JsonGenerationException e) { e.printStackTrace(); } catch (JsonMappingException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } |
相应的 jar 包引入:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; import java.util.HashMap; import java.util.Map; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通