案例1:
前端页面
<div> <form class="form-signin" id="addSongFormId" enctype="multipart/form-data" method="post"> 歌曲: <input type="file" id="fileSongId" class="custom-file-input" name="song"> 歌手: <input type="text" class="form-control mr-sm-2" name="songAuthor"> 类型: <select class="custom-select-override " name="songLanguageType"> <option value="1">华语</option> <option value="2">日韩</option> <option value="3">欧美</option> </select> </form> </div>
js代码
<script> $(function () { //处理上传 var maxSongSize = 1024 * 1024 * 20;//文件最大10M var songFormat = ["mp3"]; $("#addSongFormId").submit(function () { var song = $('#fileSongId').get(0).files[0]; //判定格式 if (song == null) { $('#collapse-file-error-hint').html("请选择歌曲文件"); $('#collapse-file-error-hint').collapse(); return false; } else if (song.size > maxSongSize) { $('#collapse-file-error-hint').html("超出文件最大限制"); $('#collapse-file-error-hint').collapse(); return false; } else if (songFormat.indexOf(song.name.substr(song.name.lastIndexOf(".") + 1)) == -1) { $('#collapse-file-error-hint').html("歌曲文件格式不对"); $('#collapse-file-error-hint').collapse(); return false; } else { } //提交 url = "frontaddSong"; /** * var data=$('#addSongFormId').serialize(); * 序列化的方式,表单里有文件的时候就不行了,可以用FormData对象 */ var data = new FormData(document.getElementById("addSongFormId")); //var data = new FormData($('#addSongFormId')); $.ajax({ type: "POST", url: url, data: data, processData: false, contentType: false, success: function (data) { var res = JSON.parse(data); if (res.status == 200) { $('#collapse-file-error-hint').html(res.msg); $('#collapse-file-error-hint').collapse() alert("上传成功"); $("#UpModalCenter").modal('hide'); // window.location.reload(); $('#list-upload').load("uploadFrameLoad.do"); } else { $('#collapse-file-error-hint').html(res.msg); $('#collapse-file-error-hint').collapse() } } }); return false; });//处理上传 End }); </script>
后台代码:
/** * 添加歌曲 * * @param request * @param song * @return */ @PostMapping(value = "frontaddSong") @ResponseBody public String addSong(HttpServletRequest request, String songAuthor, Integer songLanguageType, MultipartFile song) { String name = song.getOriginalFilename(); //歌曲名称需去掉.mp3的后缀 String songName = name.substring(0, name.lastIndexOf(".")); //这里上传至webapp下的track/song文件夹下 String songAddress = "track/song/" + name; User user = (User) request.getSession().getAttribute("user"); Song song1 = new Song(songName, songAddress, songLanguageType, 1, 0, user.getUserId(), songAuthor, 0, 0); int result = songDao.insertOnlySong(song1); if (result > 0) { saveFile(song, request.getServletContext().getRealPath(songAddress)); return ReturnMsg.msg(HttpServletResponse.SC_OK, "上传成功"); } else { return ReturnMsg.msg(HttpServletResponse.SC_BAD_GATEWAY, "上传失敗"); } } private void saveFile(MultipartFile multipartFile, String realFilePath) { try { //使用输入输出缓冲流提高上传效率 InputStream fis = multipartFile.getInputStream(); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream(realFilePath); BufferedOutputStream bos = new BufferedOutputStream(fos); int size = 0; byte[] buffer = new byte[10240]; while ((size = bis.read(buffer)) != -1) { bos.write(buffer, 0, size); } //刷新此缓冲的输出流,保证数据全部都能写出 bos.flush(); bis.close(); bos.close(); } catch (IOException e) { throw new RuntimeException(e); } }
文件下载
//download.do?songAddress=track/song/毛不易 - 无问.mp3&songId=290 @RequestMapping(value = "download.do", method = { RequestMethod.GET}) public void download(HttpServletRequest request,HttpServletResponse response,String songAddress,int songId) throws IOException { response.setContentType("audio/mp3"); response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(System.currentTimeMillis()+"如果不想返回名称的话.mp3", "utf8")); BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream()); InputStream bis=null; if(songAddress.contains("http")) { //在另外服务器的文件 URL url = new URL(songAddress); URLConnection uc = url.openConnection(); bis=new BufferedInputStream(uc.getInputStream()); }else { //在服务器内部的文件 songAddress=request.getServletContext().getRealPath(songAddress); bis = new BufferedInputStream(new FileInputStream(new File(songAddress))); } int len = 0; while((len = bis.read()) != -1){ out.write(len); out.flush(); } out.close(); bis.close(); }
案例二:
读写指定路径的文件
public static void main(String[] args){ /** * 1.先将文件中的内容读入到缓冲输入流中 * 2.将输入流中的数据通过缓冲输出流写入到目标文件中 * 3.关闭输入流和输出流 */ try { long begin=System.currentTimeMillis(); FileInputStream fis=new FileInputStream("BISDemo.txt"); BufferedInputStream bis=new BufferedInputStream(fis); FileOutputStream fos=new FileOutputStream("BOSDemo.txt"); BufferedOutputStream bos=new BufferedOutputStream(fos); int size=0; byte[] buffer=new byte[10240]; while((size=bis.read(buffer))!=-1){ bos.write(buffer, 0, size); } //刷新此缓冲的输出流,保证数据全部都能写出 bos.flush(); bis.close(); bos.close(); long end=System.currentTimeMillis(); System.out.println("使用缓冲输出流和缓冲输入流实现文件的复制完毕!耗时:"+(end-begin)+"毫秒"); } catch (Exception e) { e.printStackTrace(); } }
案例三:springmvc中后台如何接受上传文件方法
private void saveFile(MultipartFile multipartFile, String realFilePath) { try { InputStream fis = multipartFile.getInputStream(); BufferedInputStream bis = new BufferedInputStream(fis); FileOutputStream fos = new FileOutputStream(realFilePath); BufferedOutputStream bos = new BufferedOutputStream(fos); int size = 0; byte[] buffer = new byte[10240]; while ((size = bis.read(buffer)) != -1) { bos.write(buffer, 0, size); } //刷新此缓冲的输出流,保证数据全部都能写出 bos.flush(); bis.close(); bos.close(); } catch (IOException e) { throw new RuntimeException(e); } }
案例四:异步上传文件
表单html
<form id="addcropform" class="add-article-form" enctype="multipart/form-data"> <input type="hidden" value="${crop.id}" name="id"> <div class="col-md-9"> <h1 class="page-header">农作物编辑</h1> <div class="form-group"> <p style="font-size: 16px;margin-bottom: 5px;">农作物名称</p> <input type="text" id="title" name="title" value="${crop.title}" class="form-control" required="required" placeholder="名称"> </div> <div class="form-group"> <label for="category-fname">农作物类别</label> <select id="category-fname" class="form-control" name="typeid" style="width: 240px;margin-bottom: 10px"> <option value="">请选择</option> <c:forEach items="${types}" var="t"> <c:if test="${t.parentid==1}"> <option value="${t.id}" ${crop.typeid==t.id?'selected' : ''}>${t.name}</option> </c:if> </c:forEach> </select> </div> <div class="form-group"> <p style="font-size: 16px;margin-bottom: 5px;">特性</p> <input type="text" name="feature" value="${crop.feature}" class="form-control" placeholder="特性" required="required"> </div> <div class="form-group"> <p style="font-size: 16px;margin-bottom: 5px;">生长环境</p> <input type="text" name="environment" value="${crop.environment}" class="form-control" placeholder="生长环境" required="required"> </div> <div class="form-group"> <p style="font-size: 16px;margin-bottom: 5px;">产地</p> <input type="text" name="location" value="${crop.location}" class="form-control" placeholder="产地" required="required"> </div> <div class="form-group"> <p style="font-size: 16px;margin-bottom: 5px;">图片</p> <img src="<%=path %>${crop.img}" style="width: 80px;"> <input type="file" name="img" value="<%=path %>${crop.img}"> </div> <div class="form-group"> <div id="editor" class="layui-input-block" style="background: white;"> <p>${crop.info}</p> </div> <div class="layui-input-block"> <textarea style="width:700px;height:100px;visibility:hidden;" name="info" id="text1"></textarea> </div> <script type="text/javascript"> var E = window.wangEditor; var editor = new E('#editor'); // 或者 var editor = new E( document.getElementById('editor') ) editor.customConfig.uploadImgShowBase64 = true; // 使用 base64 保存图片 var $text1 = $('#text1') editor.customConfig.onchange = function (html) { // 监控变化,同步更新到 textarea $text1.val(html) } editor.create(); $text1.val(editor.txt.html()); </script> </div> </div> <div class="col-md-3"> <h1 class="page-header">操作</h1> <div class="add-article-box-footer"> <button class="btn btn-primary" type="button" onclick="addCrop()" name="submit">发布 </button> </div> </div> </form>
js代码
<script> function addCrop() { var title = $("#title").val(); if (!title) { alert("名称不能为空"); return; } var formdata = new FormData($("#addcropform")[0]); $.ajax({ type: "POST",//方法类型 dataType: "json",//预期服务器返回的数据类型 url: "/admin/addcrop",//url data: formdata, async: false, cache: false, contentType: false, processData: false, success: function (result) { console.log(result);//打印服务端返回的数据(调试用) if (result.status == 200) { alert("提交成功"); window.location.reload(); } else { alert(result.msg); } }, error: function () { alert("异常!"); } }); } </script>
后端代码
@ResponseBody @PostMapping("/addcrop") public Result addcrop(Integer id, HttpServletRequest request, String title, String info, Integer typeid, String feature, String location, String environment, @RequestParam("img") MultipartFile img) throws IOException { if (id != null) { //修改 String fileName = null; if (!img.isEmpty()) { //根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了 fileName = System.currentTimeMillis() + img.getOriginalFilename(); //通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名,这个是web项目情况 如果是jar项目,不能使用这个 String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName; File destFile = new File(destFileName); //把浏览器上传的文件复制到希望的位置 img.transferTo(destFile); //6.把文件名放在model里,以便后续显示用 } Crop crop=null; if(img.getOriginalFilename().equals("")){ crop = new Crop(id, title, null, info, new Date(), typeid, feature, location, environment); }else{ crop = new Crop(id, title, "/upload/" + fileName, info, new Date(), typeid, feature, location, environment); } cropMapper.updateByPrimaryKey(crop); return new Result(200); } else {//添加 String fileName = null; if (!img.isEmpty()) { //根据时间戳创建新的文件名,这样即便是第二次上传相同名称的文件,也不会把第一次的文件覆盖了 fileName = System.currentTimeMillis() + img.getOriginalFilename(); //通过req.getServletContext().getRealPath("") 获取当前项目的真实路径,然后拼接前面的文件名 String destFileName = request.getServletContext().getRealPath("") + "upload" + File.separator + fileName; File destFile = new File(destFileName); //把浏览器上传的文件复制到希望的位置 img.transferTo(destFile); } Crop crop = new Crop(id, title, "/upload/" + fileName, info, new Date(), typeid, feature, location, environment); cropMapper.insert(crop); return new Result(200); } }
大文件上传
https://mp.weixin.qq.com/s/h2ZxO1VDDVQKd4LxRFmcDw