话不多说,直接上代码。
1.java后台
package com.bjhit.eranges.actions.test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
public class UploadifyTestAction extends ActionSupport {
private static final long serialVersionUID = 837481714629791752L;
private File file;
private String fileName;
private String fileSize;
private String uploadSize;
private String responseInfo;
public String getUploadedSize() throws IOException{
uploadSize = "0";
File newFile = new File("D:\\"+fileName);
File fileUploadDetal = new File("D:\\"+fileName+".rhxy");//临时文件,记录文件上传的状态
if (newFile.exists()) {
if (!fileUploadDetal.exists()) {
//此文件夹下有重名文件,不允许上传
return "falier";
}else{
FileReader fileReader = new FileReader(fileUploadDetal);
BufferedReader bufferedReader = new BufferedReader(fileReader);
bufferedReader.readLine();
String name = bufferedReader.readLine();
bufferedReader.readLine();
String size = bufferedReader.readLine();
bufferedReader.readLine();
String uploadedSize = bufferedReader.readLine();
bufferedReader.readLine();
String createTime = bufferedReader.readLine();
bufferedReader.close();
fileReader.close();
System.out.println("文件:"+name+" "+size+"字节, 已上传"+uploadedSize+"字节,更新时间"+createTime);
if (name.equals(fileName)) {
uploadSize = uploadedSize;
}else{
System.out.println("文件:"+fileName+" 上传信息有错误。");
}
}
}
return "uploadsize";
}
public String doUpload() throws Exception {
System.out.println("=======================================");
System.out.println(fileName);
System.out.println(file.length()+",已传大小:"+uploadSize);
File newFile = new File("D:\\"+fileName);
File fileUploadDetal = new File("D:\\"+fileName+".rhxy");//临时文件,记录文件上传的状态
if (!newFile.exists()) {
newFile.createNewFile();
}else{
if (!fileUploadDetal.exists()) {
//此文件夹下有重名文件,不允许上传
return "falier";
}
}
copyFile(file,newFile);
if (uploadSize.equals(fileSize)) {
fileUploadDetal.delete();
}else{
if (!fileUploadDetal.exists()) {
fileUploadDetal.createNewFile();
}
FileWriter fileWriter = new FileWriter(fileUploadDetal);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("文件名:");
bufferedWriter.newLine();
bufferedWriter.write(fileName);
bufferedWriter.newLine();
bufferedWriter.write("文件大小:");
bufferedWriter.newLine();
bufferedWriter.write(fileSize);
bufferedWriter.newLine();
bufferedWriter.write("已传大小:");
bufferedWriter.newLine();
bufferedWriter.write(uploadSize);
bufferedWriter.newLine();
bufferedWriter.write("更新时间:");
bufferedWriter.newLine();
bufferedWriter.write(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
bufferedWriter.close();
fileWriter.close();
}
responseInfo = "上传成功!";
return "doUpload";
}
private void copyFile(File oldFile,File newFile) throws IOException{
InputStream in = new FileInputStream(oldFile);
OutputStream out = new FileOutputStream(newFile,true);
byte[] buffer = new byte[1024];
int len = -1;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getResponseInfo() {
return responseInfo;
}
public void setResponseInfo(String responseInfo) {
this.responseInfo = responseInfo;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileSize() {
return fileSize;
}
public void setFileSize(String fileSize) {
this.fileSize = fileSize;
}
public String getUploadSize() {
return uploadSize;
}
public void setUploadSize(String uploadSize) {
this.uploadSize = uploadSize;
}
}
2.struts2配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<include file="*_struts.xml" />
<constant name="struts.devMode" value="true" />
<constant name="struts.objectFactory" value="spring"/>
<constant name="struts.i18n.encoding" value="UTF-8"/>
<constant name="struts.multipart.maxSize" value="1073741824"/>
<package name="test" extends="struts-default,json-default" namespace="/" >
<!-- 文件上传例子 -->
<action name="uploadifyTest_*" class="com.bjhit.eranges.actions.test.UploadifyTestAction" method="{1}">
<result name="doUpload" type="json">
<param name="includeProperties">responseInfo</param>
<param name="excludeNullProperties">true</param>
</result>
<result name="uploadsize" type="json">
<param name="includeProperties">uploadSize</param>
<param name="excludeNullProperties">true</param>
</result>
</action>
</package>
</struts>
3.前台上传
<%@page language="java" pageEncoding="UTF-8"
contentType="text/html; charset=UTF-8"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html>
<html>
<head>
<title>使用XMLHttpRequest上传文件</title>
<script type="text/javascript">
var xhr = new XMLHttpRequest();
//监听选择文件信息
function fileSelected() {
//HTML5文件API操作
var file = document.getElementById('file').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadMaxFile(){
var testxhr = new XMLHttpRequest();
var file = document.getElementById('file').files[0];
if (file) {
var fd = new FormData();
fd.append("fileName", file.name);
fd.append("fileSize", file.size);
testxhr.onload = function(evt){
var start = parseInt(JSON.parse(evt.target.responseText).uploadSize);
uploadFile(file,start);
};
testxhr.open("POST", "../uploadifyTest_getUploadedSize.action");
testxhr.send(fd);
}
}
//上传文件
function uploadFile(file,start) {
var fd = new FormData();
//关联表单数据,可以是自定义参数
fd.append("fileName", file.name);
fd.append("fileSize", file.size);
var end = start + 1024*1024;//文件分片上传,每片1M
var endFlag = false;
if(end>=file.size){
end = file.size;
endFlag = true;
}
fd.append("file", file.slice(start,end));
fd.append("uploadSize", end);
//监听事件
//xhr.upload.addEventListener("progress", uploadProgress, false);
//xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.onload = function(evt){
if(!endFlag){
uploadFile(file,end);
}
};
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
//var percentComplete = Math.round(evt.loaded * 100 / evt.total);
var percentComplete = Math.round((evt.loaded+start) * 100 / file.size);
document.getElementById('progressNumber').innerHTML = percentComplete
.toString()
+ '%';
} else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}, false);
//发送文件和表单自定义参数
xhr.open("POST", "../uploadifyTest_doUpload.action");
xhr.send(fd);
}
//取消上传
function cancleUploadFile() {
xhr.abort();
}
//上传进度
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete
.toString()
+ '%';
} else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
//上传成功响应
function uploadComplete(evt) {
//服务断接收完文件返回的结果
alert(evt.target.responseText);
}
//上传失败
function uploadFailed(evt) {
alert("上传失败");
}
//取消上传
function uploadCanceled(evt) {
alert("您取消了本次上传.");
}
</script>
</head>
<body>
<form id="form1" enctype="multipart/form-data" method="post"
action="upload.php">
<div class="row">
<label for="fileToUpload">选择文件</label> <input type="file"
name="file" id="file" οnchange="fileSelected();" />
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button"
οnclick="uploadMaxFile()" value="上传" /> <input type="button"
οnclick="cancleUploadFile()" value="取消" />
</div>
<div id="progressNumber"></div>
</form>
</body>
</html>