Fork me on GitHub

文件的上传和下载

文件的上传和下载

文件上传

选择 文件之后回显

html

1
2
3
4
5
6
7
8
9
10
<script type="text/javascript" src="../../../sunriseui.js"></script>
<script type="text/javascript">
load('ajaxfileupload');
</script>
....
<div id="divPreview">
<input id="iconPic1" name="picUrl" type="hidden"/>
<img id="imgHeadPhoto" src="" style="width: 320px; height: 130px; border: solid 1px #d2e2e2;" alt="" />
</div>
<input id="files" name="files" type="file" size="20" onchange="PreviewImage(this,'imgHeadPhoto','divPreview');"/>

js

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//js本地图片预览,兼容ie[6-9]、火狐、Chrome17+、Opera11+、Maxthon3
function PreviewImage(fileObj, imgPreviewId, divPreviewId) {
//允许上传文件的后缀名
var allowExtention = ".jpg,.bmp,.gif,.png";
var extention = fileObj.value.substring(fileObj.value.lastIndexOf(".") + 1).toLowerCase();
var browserVersion = window.navigator.userAgent.toUpperCase();
if (allowExtention.indexOf(extention) > -1) {
//HTML5实现预览,兼容chrome、火狐7+等
if (fileObj.files) {
if (window.FileReader) {
var reader = new FileReader();
reader.onload = function (e) {
/*var pcBase64Text = e.target.result;
var blob = dataURLtoBlob(pcBase64Text);
console.log(e.target.result);*/
$("#iconPic1").val(e.target.result);
document.getElementById(imgPreviewId).setAttribute("src",e.target.result);
}
//读取文件把问价转换成 Base64 格式
reader.readAsDataURL(fileObj.files[0]);
}else if (browserVersion.indexOf("SAFARI") > -1) {
alert("不支持Safari6.0以下浏览器的图片预览!");
}
}else if (browserVersion.indexOf("MSIE") > -1) {
// 兼容 IE6 浏览器
if (browserVersion.indexOf("MSIE 6") > -1) {
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
}else{ // 兼容 IE[7-9] 浏览器
fileObj.select();
if(browserVersion.indexOf("MSIE 9") > -1){
//不加上document.selection.createRange().text在ie9会拒绝访问
fileObj.blur();
}
var newPreview = document.getElementById(divPreviewId + "New");
if(newPreview == null){
newPreview = document.createElement("div");
newPreview.setAttribute("id", divPreviewId + "New");
newPreview.style.width = document.getElementById(imgPreviewId).width + "px";
newPreview.style.height =
document.getElementById(imgPreviewId).height + "px";
newPreview.style.height =
document.getElementById(imgPreviewId).height + "px";
}
newPreview.style.filter =
"progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',
src='" + document.selection.createRange().text + "')";
var tempDivPreview = document.getElementById(divPreviewId);
tempDivPreview.parentNode.insertBefore(newPreview, tempDivPreview);
tempDivPreview.style.display = "none";
}
}else if (browserVersion.indexOf("FIREFOX") > -1) {
var firefoxVersion =
parseFloat(browserVersion.toLowerCase().match(/firefox\/([\d.]+)/)[1]);
//firefox7以下版本
if (firefoxVersion < 7) {
document.getElementById(imgPreviewId).
setAttribute("src", fileObj.files[0].getAsDataURL());
}else {//firefox7.0+
document.getElementById(imgPreviewId).
setAttribute("src", window.URL.createObjectURL(fileObj.files[0]));
}
}else {
document.getElementById(imgPreviewId).setAttribute("src", fileObj.value);
}
}else {
alert("仅支持" + allowExtention + "为后缀名的文件!");
fileObj.value = ""; //清空选中文件
if (browserVersion.indexOf("MSIE") > -1) {
fileObj.select();
document.selection.clear();
}
fileObj.outerHTML = fileObj.outerHTML;
}
return fileObj.value; //返回路径
}

这段代码里面我只用到 第一个判断 兼容chrome、火狐7+ ,使用文件内改变事件。

使用 ajaxfileupload.js 进行异步上传

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//后台请求
function uploadFile(){
return getHost(HostAddress.uomp) + '/uomp/keeperAdvertInfo/uploadFile';
}
$.ajaxFileUpload({
url:uploadFile(),
type:'post',
secureuri : false, // 是否需要安全协议,一般设置为false
id : "filesform",
fileElementId : 'files', // 文件上传域的ID
dataType : 'JSON', // 返回值类型 一般设置为json
data : { // 请求后台接口要带的参数
uploadpath:'keeper',
fileName:fn
},
async : false,
success : function(data) {},
error : function(data, status) {}
});

后台文件上传的上传的实现

文件辅助类

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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.eyuninfo.framework.common.SysConstant;
public class FileUtil {
private static Log log = LogFactory.getLog(FileUtil.class);
public static boolean uploadfile(InputStream in, String filePath) {
boolean res = false;
try {
if (in != null) {
File file = new File(filePath);
int bytesRead = 0;
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
in.close();
res = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 读取文本文件
*
* @param txtPath 文本文件路径
* @return 文本内容
* @author michael 20161103 from kbms
*/
public static String readTxt(String txtPath) {
StringBuilder content = new StringBuilder();
InputStreamReader read = null;
try {
if (txtPath != null && !txtPath.isEmpty()) {
// String encoding=codeString(txtPath);
File file = new File(txtPath);
if (file.isFile() && file.exists()) { // 判断文件是否存在
read = new InputStreamReader(new FileInputStream(file));// 考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while ((lineTxt = bufferedReader.readLine()) != null) {
content.append(lineTxt);
}
read.close();
} else {
log.info("找不到指定的文件");
}
} else {
log.debug("txtPath 不能为空");
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
}
return content.toString();
}
/**
* 获取文件编码
*
* @param fileName
* @return
* @throws Exception
* @author michael 20161103 from kbms
*/
public static String codeString(String fileName) throws Exception {
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(fileName));
int p = (bin.read() << 8) + bin.read();
String code = null;
// 其中的 0xefbb、0xfffe、0xfeff、0x5c75这些都是这个文件的前面两个字节的16进制数
switch (p) {
case 0xefbb:
code = "UTF-8";
break;
case 0xfffe:
code = "Unicode";
break;
case 0xfeff:
code = "UTF-16BE";
break;
case 0x5c75:
code = "ANSI|ASCII";
break;
default:
code = "GBK";
}
return code;
}
/**
* 创建目录
*
* @param dir 目录
* @return boolean 创建结果
* @author michael 20161103 from kbms
*/
public static boolean mkDir(File dir) {
if (!dir.getParentFile().exists()) {
mkDir(dir.getParentFile());
}
return dir.mkdir();
}
/**
* 获取某文件夹下的所有文件(递归,含子文件)
*
* @param file
* @param resultFileName
* @return 文件名称列表
*/
public static List<String> getFiles(File file, List<String> resultFileName) {
try {
File[] files = file.listFiles();
if (files == null)
return resultFileName;// 判断目录下是不是空的
for (File f : files) {
if (f.isDirectory()) {// 判断是否文件夹
resultFileName.add(f.getPath());
getFiles(f, resultFileName);// 调用自身,查找子目录
} else {
resultFileName.add(f.getPath());
}
}
} catch (Exception e) {
e.printStackTrace();
}
return resultFileName;
}
/**
* 文件复制
*
* @param source 原文件
* @param target 目标文件
* @author michael 20161103 from kbms
*/
public static void copy(File source, File target) {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new BufferedInputStream(new FileInputStream(source));
fos = new BufferedOutputStream(new FileOutputStream(target));
byte[] buf = new byte[4096];
int i;
while ((i = fis.read(buf)) != -1) {
fos.write(buf, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
} finally {
try {
fis.close();
fos.close();
log.info("已经复制文件:" + source.getPath() + " 到 " + target.getPath());
} catch (Exception ioe) {
ioe.printStackTrace();
log.error(ioe.getMessage());
}
}
}
/**
* 删除文件夹里面所有内容
* @param path
* @return
* @author michael 20161103 from kbms
*/
public static boolean delAllFile(String path) {
boolean flag = false;
File file = new File(path);
if (!file.exists()) {
return flag;
}
if (!file.isDirectory()) {
return flag;
}
String[] tempList = file.list();
File temp = null;
for (int i = 0; i < tempList.length; i++) {
if (path.endsWith(File.separator)) {
temp = new File(path + tempList[i]);
} else {
temp = new File(path + File.separator + tempList[i]);
}
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
//先删除文件夹里面的文件
delAllFile(path + SysConstant.FILE_SEPARATOR + tempList[i]);
flag = true;
}
}
return flag;
}
/**
* 创建Txt文件
* @param name 文件名
* @param text
* @return
*/
public static String createTxtFile(String name,String text){
try{
String docPath=SysConstant.config.getProperty("txtPath");
if(docPath!=null){
boolean re=true;
docPath = docPath+SysConstant.FILE_SEPARATOR+DateUtil.getDate("");
File docFile=new File(docPath);
if(!docFile.exists()){
re= docFile.mkdirs();
}
if(re){
//结构化数据保存为txt文档用于创建文件索引
docPath+=SysConstant.FILE_SEPARATOR+name+".txt";
InputStream inputStream = InputStreamUtils.StringToInputStream(text);
if(uploadDoc(inputStream,docPath)) return docPath;else{
return null;
}
}else{
log.error("docPath不存在"+docPath);
return null;
}
}else{
log.error("配置文件SysConstant不存在 docPath 参数");
return null;
}
}catch(Exception e){
e.printStackTrace();
return null;
}
}
private static boolean uploadDoc(InputStream in,String filePath){
boolean res= false;
try{
if(in!=null){
File file = new File(filePath);
if(file.exists()){
file.createNewFile();
}
log.info("docPath:::>>"+filePath);
int bytesRead = 0;
OutputStream os = new FileOutputStream(file);
byte[] buffer = new byte[8192];
while ((bytesRead = in.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
in.close();
res= true;
}
}catch(Exception e){
e.printStackTrace();
log.error(e.getMessage());
}
return res;
}
}

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
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST,produces="text/plain;charset=UTF-8")
@ResponseBody
public ResultBean<LogImportBean> uploadFile(Locale locale,@RequestParam("uploadpath") String uploadpath,
@RequestParam("fileName") String fileName,@RequestParam MultipartFile[] files, Model model) {
ResultBean<LogImportBean> rb=new ResultBean<LogImportBean>();
try {
String rootpatch=
SysConstant.config.getProperty("rootuplaodfile")+File.separator+uploadpath;
File rootfile=new File(rootpatch);
if(!rootfile.exists()){
if(rootfile.mkdirs()){
log.info("创建文件夹成功:"+rootpatch);
}else{
log.info("创建文件夹失败:"+rootpatch);
}
}
if(new File(rootpatch).exists()){
String filepath=rootpatch+File.separator+fileName;
if(FileUtil.uploadfile(files[0].getInputStream(),filepath)){
rb.setBean(new LogImportBean(0, "保存附件成功!"));
rb.setReturnCode(SysConstant.SYS_RETURN_SUCCESS_CODE);
rb.setReturnMessage(SysConstant.SYS_RETURN_SUCCESS_MESSAGE);
}else{
rb.setBean(new LogImportBean(0, "保存附件失败!"));
rb.setReturnCode(SysConstant.SYS_RETURN_FAILED_CODE);
}
}else{
rb.setReturnCode(SysConstant.SYS_RETURN_FAILED_CODE);
rb.setReturnCode("rootpatch文件夹不存在:"+rootpatch);
}
} catch (Exception e) {
e.printStackTrace();
}
return rb;
}

文件下载

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
@RequestMapping(value = "/downloadFile", method = RequestMethod.GET)
public ResponseEntity<byte[]> downloadFile(Locale locale,
@RequestParam("uploadpath") String uploadpath,
@RequestParam("fileName") String fileName, Model model){
try {
String rootpatch=
SysConstant.config.getProperty("rootuplaodfile")+File.separator+uploadpath;
String filepath=rootpatch+File.separator+fileName;
HttpHeaders headers = new HttpHeaders();
MediaType mt=new MediaType("application","octet-stream");
headers.setContentType(mt);
fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
headers.setContentDispositionFormData("attachment",fileName);
File file=new File(filepath);
if(file.exists()){
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
}else{
return new ResponseEntity<byte[]>(null, headers, HttpStatus.FAILED_DEPENDENCY);
}
} catch (Exception e) {
e.printStackTrace();
return new ResponseEntity<byte[]>(null, null, HttpStatus.FAILED_DEPENDENCY);
}
}
坚持原创技术分享,您的支持将鼓励我继续创作!