java怎么把文件传输到服务器
String realpath = ServletActionContextgetServletContext()getRealPath("/upload") ;//获取服务器路径
String[] targetFileName = uploadFileName;
for (int i = 0; i < uploadlength; i++) {
File target = new File(realpath, targetFileName[i]);
FileUtilscopyFile(upload[i], target);
//这是一个文件复制类copyFile()里面就是IO操作,如果你不用这个类也可以自己写一个IO复制文件的类
}
其中private File[] upload;// 实际上传文件
private String[] uploadContentType; // 文件的内容类型
private String[] uploadFileName; // 上传文件名
这三个参数必须这样命名,因为文件上传控件默认是封装了这3个参数的,且在action里面他们应有get,set方法
在jsp/servlet中断点/多线程下载文件
<%@ page import="javaioFile" %><%@ page import="javaioIOException" %>
<%@ page import="javaioOutputStream" %>
<%@ page import="javaioRandomAccessFile" %>
<%!
public void downloadFile(HttpServletRequest request, HttpServletResponse response, File file) throws IOException {
RandomAccessFile raf = new RandomAccessFile(file, "r");
javaioFileInputStream fis = new javaioFileInputStream(rafgetFD());
responsesetHeader("Server", "wwwtrydonecom");
responsesetHeader("Accept-Ranges", "bytes");
long pos = 0;
long len;
len = raflength();
if (requestgetHeader("Range") != null) {
responsesetStatus(HttpServletResponseSC_PARTIAL_CONTENT);
pos = LongparseLong(requestgetHeader("Range")
replaceAll("bytes=", "")
replaceAll("-", "")
);
}
responsesetHeader("Content-Length", LongtoString(len - pos));
if (pos != 0) {
responsesetHeader("Content-Range", new StringBuffer()
append("bytes ")
append(pos)
append("-")
append(LongtoString(len - 1))
append("/")
append(len)
toString()
);
}
responsesetContentType("application/octet-stream");
responsesetHeader("Content-Disposition", new StringBuffer()
append("attachment;filename=\"")
append(filegetName())
append("\"")toString());
rafseek(pos);
byte[] b = new byte[2048];
int i;
OutputStream outs = responsegetOutputStream();
while ((i = rafread(b)) != -1) {
outswrite(b, 0, i);
}
rafclose();
fisclose();
}
%>
<%
String filePath = requestgetParameter("file");
filePath = applicationgetRealPath(filePath);
File file = new File(filePath);
downloadFile(request, response, file);
%>
0条评论