java实现文件的跨域上传
第一步:创建文件上传的表单以及上传的控件代码如下:
<form action="后台地址" enctype="multipart/form-data" method="post">
<ul>
<li><span>上传文件</span><input id="resource" name="Resource" type="file" accept="*" value="选择文件" /></li>
</ul>
<input type="submit" name="Submit" value="提交">
</form>
这个代码中首先注意的是表单提交时enctype="multipart/form-data"表单中enctype="multipart/form-data"的意思,是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能用于文件上传;只有使用了multipart/form-data,才能完整的传递文件数据,进行下面的操作. accept="*"代表上传文件的类型可以限制只上传图片或者特定类型的文件。第二步:后台处理表单提交来的数据实现文件的上传,代码如下:
<pre name="code" class="html">public class TSUpload extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private File Resource;
private String ResourcePath;
private HttpServletRequest request;
@SuppressWarnings("resource")
public String upload(){
request = ServletActionContext.getRequest();
String _initpath = request.getServletContext().getInitParameter("FileSavePath");
this.setResourcePath(_initpath);
String filename="test";
FileInputStream _input = null;
FileOutputStream _output = null;
try {
//根据文件的路径获取到文件并转换成io流,再创建io输出流用以存放读取到的输入流。
ActionContext.getContext().getSession().put("fileprogress", "0.0000");
_output = new FileOutputStream(this.getResourcePath() + "\\" + filename);
_input = new FileInputStream(this.getResource());
String _size = "";
//获取文件的大小
if (this.getResource().length()/1024>1&&this.getResource().length()/1024<1024) {
_size = this.getResource().length()/1024 + " KB";
} else if (this.getResource().length()/1024/1024>=1&&this.getResource().length()/1024/1024<1024) {
_size = this.getResource().length()/1024/1024 + " MB";
}
System.out.println("------>>>>>> Tomcat Catalina File Size: " + _size); // 服务器临时文件大小
byte[] _buffer = new byte[8192];
int _length = 0;
int _index = 0;
while ((_length = _input.read(_buffer))>0) {
_output.write(_buffer, 0, _length);
_index ++;
double _filesize = this.getResource().length();
double _readsize = _index*8192;
double _progress = _readsize/_filesize*100;
DecimalFormat _df = new DecimalFormat("#.0000");
/*BigDecimal _fomat = new BigDecimal(_tempprogress);*/
ActionContext.getContext().getSession().put("fileprogress", _df.format(_progress));
}
}catch(Exception e){
e.printStackTrace();
}
return "success";
}
public File getResource() {
return Resource;
}
public void setResource(File resource) {
Resource = resource;
}
public String getResourcePath() {
return ResourcePath;
}
public void setResourcePath(String resourcePath) {
ResourcePath = resourcePath;
}
}
简单的文件上传就实现了,关键是前台表单提交的模式以及后台处理的方法。路径可以自己设置,最好获取配置文件中的路径到时更改也方便,也可以根据需要返回想要的具体的保存好的文件路径直接用以获取文件。