1 public class FileUtil {
2
3
4 /**
5 * 读取文件内容,作为字符串返回
6 */
7 public static String readFileAsString(String filePath) throws IOException {
8 File file = new File(filePath);
9 if (!file.exists()) {
10 throw new FileNotFoundException(filePath);
11 }
12
13 if (file.length() > 1024 * 1024 * 1024) {
14 throw new IOException("File is too large");
15 }
16
17 StringBuilder sb = new StringBuilder((int) (file.length()));
18 // 创建字节输入流
19 FileInputStream fis = new FileInputStream(filePath);
20 // 创建一个长度为10240的Buffer
21 byte[] bbuf = new byte[10240];
22 // 用于保存实际读取的字节数
23 int hasRead = 0;
24 while ( (hasRead = fis.read(bbuf)) > 0 ) {
25 sb.append(new String(bbuf, 0, hasRead));
26 }
27 fis.close();
28 return sb.toString();
29 }
30
31 /**
32 * 根据文件路径读取byte[] 数组
33 */
34 public static byte[] readFileByBytes(String filePath) throws IOException {
35 File file = new File(filePath);
36 if (!file.exists()) {
37 throw new FileNotFoundException(filePath);
38 } else {
39 ByteArrayOutputStream bos = new ByteArrayOutputStream((int) file.length());
40 BufferedInputStream in = null;
41
42 try {
43 in = new BufferedInputStream(new FileInputStream(file));
44 short bufSize = 1024;
45 byte[] buffer = new byte[bufSize];
46 int len1;
47 while (-1 != (len1 = in.read(buffer, 0, bufSize))) {
48 bos.write(buffer, 0, len1);
49 }
50
51 byte[] var7 = bos.toByteArray();
52 return var7;
53 } finally {
54 try {
55 if (in != null) {
56 in.close();
57 }
58 } catch (IOException var14) {
59 var14.printStackTrace();
60 }
61
62 bos.close();
63 }
64 }
65 }
66
67 /*
68 * 通过流的方式上传文件
69 * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
70 * org.springframework.web.multipart.commons.CommonsMultipartFile(类)
71 * 中间会生成临时文件,会自动删除
72 * 效率NO.3
73 * 稍微大的文件超时,jq.js会报10254错误,前端显示404不过文件可以上传
74 * 需要在在dispatcher.xml里面配置试图解析器(<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">)
75 */
76
77 public static void fileUpload1(CommonsMultipartFile file) throws IOException {
78 // FileItem fff=file.getFileItem();
79 // System.out.println(fff.getName()+"<<<<getName()>>>>");
80 // System.out.println(fff.getFieldName()+"<<<<getFieldName()>>>>>"); ;
81 // System.out.println(fff.isFormField()+"<<<<isFormField()>>>>");
82 // //在这里面规定上传文件的类型
83 // System.out.println(fff.getContentType().endsWith(".doc")+"<<<<getContentType()>>>>");
84 // System.out.println(fff.isInMemory()+"<<<<isInMemory()>>>>");
85 // System.out.println(fff.getSize()+"<<<<getSize()>>>>");
86
87 //用来检测程序运行时间
88 long startTime=System.currentTimeMillis();
89 if(file.isEmpty()){
90 System.out.println("文件不存在(或大小为0)");
91 return;
92 }
93 String renamePath=FileUtil.renameFile(file.getOriginalFilename());
94 OutputStream os = null;
95 InputStream is = null;
96 try {
97 //获取输出流
98 os=new FileOutputStream(renamePath);
99 //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
100 is=file.getInputStream();
101 int temp;
102 //一个一个字节的读取并写入
103 while((temp=is.read())!=(-1))
104 {
105 os.write(temp);
106 }
107
108
109 } catch (FileNotFoundException e) {
110 // TODO Auto-generated catch block
111 e.printStackTrace();
112 }finally{
113 os.flush();
114 os.close();
115 is.close();
116 }
117 long endTime=System.currentTimeMillis();
118 System.out.println("方法一的运行时间:"+String.valueOf(endTime-startTime)+"ms");
119 }
120
121
122 /*
123 * 采用file.Transto 来保存上传的文件【速度最快】
124 * org.springframework.web.multipart.commons.CommonsMultipartFile(类)
125 *中间会生成临时文件,会自动删除
126 * 效率NO.2
127 * 稍微大的文件超时,jq.js会报10254错误,前端显示404不过文件可以上传
128 * * 需要在在dispatcher.xml里面配置试图解析器(<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">)
129
130 */
131 public static void fileUpload2(CommonsMultipartFile file) throws IOException {
132 if(file.isEmpty()){
133 System.out.println("文件不存在");
134 return;
135 }
136 long startTime=System.currentTimeMillis();
137 String renameFilePath=FileUtil.renameFile(file.getOriginalFilename());
138 try{
139 File newFile=new File(renameFilePath);
140 //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
141 file.transferTo(newFile);
142 }catch (Exception e){
143 System.out.println("方法2上传文件转换失败");
144 }
145
146 long endTime=System.currentTimeMillis();
147 System.out.println("方法二的运行时间:"+String.valueOf(endTime-startTime)+"ms");
148
149 }
150
151 /*推荐使用使用
152 *采用spring提供的上传文件的方法
153 * package org.springframework.web.multipart.commons.CommonsMultipartResolver;
154 * 需要在在dispatcher.xml里面配置试图解析器(<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">)
155 * 中间会生成临时文件,会自动删除
156 * 支持多文件上传
157 * 速度NO.1
158 */
159
160 public static void springUpload(HttpServletRequest request) throws IllegalStateException, IOException
161 {
162 long startTime=System.currentTimeMillis();
163 //将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
164 CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
165 request.getSession().getServletContext());
166 //检查form中是否有enctype="multipart/form-data"
167 if(multipartResolver.isMultipart(request))
168 {
169 //将request变成多部分request
170 MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
171 //获取multiRequest 中所有的文件名
172 Iterator iter=multiRequest.getFileNames();
173 // List<FileItem>
174 while(iter.hasNext())
175 {
176 //一次遍历所有文件
177 MultipartFile file=multiRequest.getFile(iter.next().toString());
178 if(file!=null)
179 {
180 String renamePath= FileUtil.renameFile(file.getOriginalFilename());
181 //上传
182 file.transferTo(new File(renamePath));
183 }
184
185 }
186
187 }
188 long endTime=System.currentTimeMillis();
189 System.out.println("方法三的运行时间:"+String.valueOf(endTime-startTime)+"ms");
190
191 }
192
193 /***基于
194 * commons-fileupload
195 *commons-io
196 *上传
197 *需要注销spring的上传文件解析器
198 * 因为protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
199 * String encoding = this.determineEncoding(request);
200 * FileUpload fileUpload = this.prepareFileUpload(encoding);已经调用FileUpload进行解析封装为自己的对象MultipartParsingResult
201 * 再次List<FileItem> list = upload.parseRequest(request);解析时为空导致集合为空
202 * */
203 public static void fileUpload3(HttpServletRequest request, HttpServletResponse response){
204 //判断是不是post提交
205 boolean isMultipart =ServletFileUpload.isMultipartContent(request);
206 if (isMultipart == true) {
207 //初始化FiletItem工厂
208 FileItemFactory fif =new DiskFileItemFactory();
209 ServletFileUpload upload = new ServletFileUpload(fif);
210 upload.setHeaderEncoding("utf-8");
211 try {
212 //解析表单请求
213 List<FileItem> list = upload.parseRequest(request);
214 for (FileItem fi : list) {
215 //普通表单元素处理start
216 if (fi.isFormField()) {//判断是不是普通变淡属性
217 String fieldname = fi.getFieldName();
218 if (fieldname.equals("productNmae")) {
219 String projectName = null;
220 try {
221 projectName = fi.getString("utf-8");
222 } catch (UnsupportedEncodingException e) {
223 System.out.println("不支持utf-8编码");
224 }
225 System.out.println(projectName);
226 } else if (fieldname.equals("file")) {
227 try {
228 System.out.println(fi.getString("utf-8"));
229 } catch (UnsupportedEncodingException e) {
230 System.out.println("不支持utf-8编码");
231 }
232 ;
233 }
234 //普通表单元素处理end
235 } else {//是文件类型判断其大小,为0继续for循环
236 if (fi.getSize() == 0) {
237 continue;
238 }
239 String newFileName =FileUtil.renameFile(fi.getName());
240 try {
241 fi.write(new File(newFileName));
242 } catch (Exception e) {
243 e.printStackTrace();
244 }
245
246 }
247 }
248 } catch (FileUploadException e) {
249 e.printStackTrace();
250 }
251
252 }
253
254 }
255 /***
256 * 上传文件命名公共方法
257 * */
258 public static synchronized String renameFile(String originalFilename){
259 System.out.println("原文件名:"+originalFilename);
260 //桌面路径
261 String prefix = originalFilename.substring(originalFilename.lastIndexOf("."));
262 String newFileName =new Date().getTime()+ prefix;
263 String desktopPath= FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath()+"\\"+newFileName;
264 System.out.println("新文件名:"+newFileName);
265 return desktopPath;
266
267 }
268
269 // <!-- 多部分文件上传 -->
270 //<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
271 // <property name="maxUploadSize" value="104857600" />
272 // <property name="maxInMemorySize" value="4096" />
273 // <property name="defaultEncoding" value="UTF-8"></property>
274 //</bean>
275 }

SpringMVC IO 文件上传的更多相关文章

  1. springmvc图片文件上传接口

    springmvc图片文件上传 用MultipartFile文件方式传输 Controller package com.controller; import java.awt.image.Buffer ...

  2. SpringMVC学习--文件上传

    简介 文件上传是web开发中常见的需求之一,springMVC将文件上传进行了集成,可以方便快捷的进行开发. springmvc中对多部件类型解析 在 页面form中提交enctype="m ...

  3. springmvc实现文件上传

    springmvc实现文件上传 多数文件上传都是通过表单形式提交给后台服务器的,因此,要实现文件上传功能,就需要提供一个文件上传的表单,而该表单就要满足以下3个条件 (1)form表彰的method属 ...

  4. 关于SpringMVC的文件上传

    关于文件的上传,之前写过2篇文章,基于Struts2框架,下面给出文章链接: <关于Struts2的文件上传>:http://www.cnblogs.com/lichenwei/p/392 ...

  5. SpringMVC+ajax文件上传实例教程

    原文地址:https://blog.csdn.net/weixin_41092717/article/details/81080152 文件上传文件上传是项目开发中最常见的功能.为了能上传文件,必须将 ...

  6. Spring +SpringMVC 实现文件上传功能。。。

    要实现Spring +SpringMVC  实现文件上传功能. 第一步:下载 第二步: 新建一个web项目导入Spring 和SpringMVC的jar包(在MyEclipse里有自动生成spring ...

  7. SpringMVC之文件上传异常处理

    一般情况下,对上传的文件会进行大小的限制.如果超过指定大小时会抛出异常,一般会对异常进行捕获并友好的显示出来.以下用SpringMVC之文件上传进行完善. 首先配置CommonsMultipartRe ...

  8. 【SpringMVC】文件上传Expected MultipartHttpServletRequest: is a MultipartResolver错误解决

    本文转载自:https://blog.csdn.net/lzgs_4/article/details/50465617 使用SpringMVC实现文件上传时,后台使用了 MultipartFile类, ...

  9. 一起学SpringMVC之文件上传

    概述 在Web系统开发过程中,文件上传是普遍的功能,本文主要以一个简单的小例子,讲解SpringMVC中文件上传的使用方法,仅供学习分享使用,如有不足之处,还请指正. 文件上传依赖包 如下所示,文件上 ...

随机推荐

  1. OpenFaaS实战之一:部署

    欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...

  2. 电子物流中的EDI 应用

    电子物流中的EDI 应用 背景 EDI 全称是Electronic data interchange, 即电子数据交换.在传统企业里,很多流程上的操作或者通信一般是由纸质媒介完成的,比如说采购订单.发 ...

  3. VScode中LeetCode插件无法登录的情况

    VScode中LeetCode插件无法登录的情况 一直提示账户和密码无效,不知道什么问题. 后来发现是设置问题 在插件中找到leetcode 右键,点击setting 在界面里找到这里,将leetco ...

  4. [考试总结]noip模拟7

    为啥博客园 \(\LaTeX\) 老挂???! \(\huge{\text{菜}}\) 刚开始写 \(T1\) 的时候,在看到后缀前缀之后,直接想到 \(AC\) 自动机,在画了半个 \(trie\) ...

  5. 第二篇 -- Qt Designer界面介绍

    1. Qt Designer创建界面 2. Qt Designer全局

  6. 最长公共子序列问题(LCS)——Python实现

      # 最长公共子序列问题 # 作用:求两个序列的最长公共子序列 # 输入:两个字符串数组:A和B # 输出:最长公共子序列的长度和序列 def LCS(A,B): print('输入字符串数组A', ...

  7. 前后端数据交互利器--Protobuf

    Protobuf 介绍 Protocol Buffers(又名 protobuf)是 Google 的语言中立.平台中立.可扩展的结构化数据序列化机制. https://github.com/prot ...

  8. 关于maven打包与jdk版本的一些关系

    最近让不同JAVA版本的容器maven打包折腾的不行,终于理出了一点头绪.在这里记录下备忘. 1. Maven与jdk版本的关系 先明确一个概念,关高版本JDK运行maven,是可以打出低版本的JAV ...

  9. 几张图搞懂 NodeJS 的流

    假设我们现在要盖一座房子,我们买了一些砖块,厂家正在送货.现在我们有两个选择,一是等所有砖块都到了以后再开始动工:二是到一批砖块就开始动工,砖块到多少我们就用多少. 这两种方式哪种效率更高呢?显然是第 ...

  10. i春秋“百度杯”CTF比赛 十月场-Vld(单引号逃逸+报错注入)

    题目源代码给出了提示index.php.txt,打开拿到了一段看不太懂得东西. 图片标注的有flag1,flag2,flag3,同时还有三段字符,然后还出现了_GET,脑洞一一点想到访问 ?flag1 ...