文件上传和下载(持续更新中)

   声明:本站部分内容来自互联网,如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

26

#上传
##单文件上传

public class FileUtils {JsonObject jsonObject = new JsonObject();public static Object fileUpload(@RequestParam("multipartFile")MultipartFile multipartFile) {if(!multipartFile.isEmpty()){String fileName = multipartFile.getOriginalFilename();String path = "D:/testFile/";File targetFile = new File(path+fileName);if (!targetFile.exists()) {targetFile.mkdirs();}try {multipartFile.transferTo(targetFile);jsonObject.put("code",1);jsonObject.put("message","上传成功");} catch (Exception e) {e.printStackTrace();jsonObject.put("code",0);jsonObject.put("message","该文件不存在");}finally{return jsonObject;}//这里除了transferTo方法,也可以用字节流的方式上传文件,但是字节流比较慢,所以还是建议用transferTo
//            try {
//                //获取输出流
//                OutputStream os=new FileOutputStream(path);
//                //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
//                InputStream is=multipartFile.getInputStream();
//                byte[] buffer= new byte[1024];
//                int len = is.read(buffer);
//                while(len!=-1){
//                    os.write(buffer, 0, len);
//                }
//                os.flush();
//                os.close();
//                is.close();
//            } catch (FileNotFoundException e) {
//                // TODO Auto-generated catch block
//                e.printStackTrace();
//            }}else{jsonObject.put("code",0);jsonObject.put("message","该文件不存在");}return jsonObject;}
}
#利用MultipartHttpServletRequest来解析request中的文件
public static filesUpload(HttpServletRequest request) {CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());if(resolver.isMultipart(request)){MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;MultipartFile file = multiRequest.getFile("file");if(file.isEmpty()){}else{}}else{jsonObject.put("code",0);jsonObject.put("message","该文件不存在");}return jsonObject;
}
#文件下载列表
public Object getList() {String path = "D:/testFile";File directory = new File(path);String[] fileNames = directory.list();
}#文件下载
public static fileDownload(HttpServletRequest request,HttpServletResponse response) {String fileName = request.getParameter("fileName"); File file = new File("D:/testFile/"+fileName);response.reset();response.setContentType("application/octet-stream;charset=utf-8");response.addHeader("Content-Length",file.length());response.addHeader("Content-Disposition","attachment;filename="+new String(fileName.getBytes("utf-8"),"gb2312"));BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());//IOUtils.copy(inputStream, outputStream);Byte[] buf = new Byte[1024];int len = -1;while((len = bis.read(buf))!=-1){bos.write(buf,0,len);}bis.close();bos.flush();bos.close();
}
#没有多文件下载

图片上传:https://blog.csdn.net/weixin_41888813/article/details/85043969