您的位置:首页 > 编程语言 > Java开发

JavaWeb实现文件上传功能

2018-08-08 17:06 106 查看

JavaWeb实现文件上传功能

一、前台

1.使用input标签的完成选择文件

input 类型设置成file ,前台即可选择文件

[code]
<input name="name" type="text" />
       <br>
       <input name="name1"type="text" />
       <br>
       <input name="File1" type="file" multiple value="kkkkk"/><br> <input
type="submit" value="Upload" />
​

效果如下:

 

2.提交请求

模拟表单提交 为啥不适用ajax原因可以看文件下载功能实现链接  https://blog.csdn.net/qq_36657997/article/details/80859634中关于ajax的解释

[code]
var blob = new Blob([ fb ]);
var fd = new FormData();
this.fb = fb;
fd.append('file', blob);
fd.append('fname', encodeURI(f.name));
fd.append('flen', f.size);
// extra parameters, it is object format
this.opt = this.parent.extpara;
if (this.opt != undefined && this.opt != null && this.opt != "") {
for (x in this.opt) {
fd.append(x, this.opt[x]);
}
}
var xhr = new XMLHttpRequest();
xhr.open('post', this.url, true);
xhr.onreadystatechange = function(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
if (onSuccess) {
onSuccess(data);
}
}
}
​
}
}
xhr.send(fd);

 

二、后台

1.获取前台传来的文件

2.利用File类,将文件写到指定位置,完成上传

[code]
private String updateFile(String oid, String pid, String vid, String fid, String fname, byte[] file, String project,
String dirName, String path) throws IOException {
String destination = "D:/data";

File f = new File(destination + "/" + fname);
if (!f.exists()) {
FileUtil.createDir(destination);
FileUtil.writeFile(file, destination, fname);
}
return "success";
}
​
/**
* writeFile工具类如下所示
*/
   public static void writeFile(byte[] bytes, String dest, String filename) throws IOException {
       BufferedOutputStream buffStream = new BufferedOutputStream(new FileOutputStream(dest + "/" + filename));
       buffStream.write(bytes);
       buffStream.close();
   }
​

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: