servlet 里面实现文件上传【表单格式POST上传数据 文件】 框架问题
SERVLET是最基础的控制框架,其文件上传部分也是比较基础的函数累计 比较考验基础,先给出文件上传功能代码 供各位参考
本流程 依赖JAR包
commons-io-2.4.jar 依赖JAR包资源下载 .zip
commons-fileupload-1.2.1.jar
private final int BUFFERSIZE = 1024 * 8;
private final String splitLine = File.separator;
private String tempAttachmentFileName;
//POST函数处理 文本字段 文件混合上传 处理函数
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 计算能够上传附件的大小
int maxLen = 7 * 1024 * 1024;
String attachmentPath = "D:/upfile/";
// 得到附件
ServletOutputStream out = response.getOutputStream();
int contentLen = request.getContentLength();
if (contentLen < maxLen) {
String contentType = request.getContentType();
String boundary = getBoundary(contentType);
ServletInputStream in = request.getInputStream();
FileOutputStream fou = null;
byte[] b = new byte[BUFFERSIZE];
int result;
try {
result = in.readLine(b, 0, b.length); // 读取boundary
result = in.readLine(b, 0, b.length); // 读取Content-Disposition
String upLoadFileName = getUpLoadFileName(new String(b, 0,
result));
tempAttachmentFileName = upLoadFileName;
File ftemp = new File(attachmentPath + upLoadFileName);
if(ftemp.exists() == false){
ftemp.createNewFile();
}
fou = new FileOutputStream(attachmentPath + upLoadFileName);
result = in.readLine(b, 0, b.length); // 读取Content-Type;
result = in.readLine(b, 0, b.length); // 读取空行;
int totalRead = 0;
result = in.readLine(b, 0, b.length);
while ((new String(b, 0, result)).trim().indexOf(boundary) == -1) {
totalRead += result;
fou.write(b, 0, result);
result = in.readLine(b, 0, b.length);
}
out.println(totalRead);
fou.close();
in.close();
// 处理文件
dealFile(upLoadFileName, totalRead, attachmentPath);
} catch (Exception ex) {
System.out.print(ex.toString());
}
}
}
/*
* 得到filename
*/
private String getUpLoadFileName(String line) {
int split = line.indexOf("name=");
String tempFileName = delQuote(line.substring(split + 9, line.length())
.trim());
if (tempFileName.indexOf("\\") != -1) {
tempFileName = tempFileName.substring(tempFileName
.lastIndexOf("\\") + 1, tempFileName.length());
}
return tempFileName;
}
/*
* 得到分隔符
*/
private String getBoundary(String line) {
return line.substring(line.indexOf("boundary=") + 9, line.length())
.trim();
}
/*
* 去除""
*/
private String delQuote(String line) {
if (line.indexOf("\"") != -1) {
line = line.substring(1, (line.length() - 1));
}
return line;
}
/*
* 处理文件,把最后的两个字节删除
*/
private void dealFile(String fileName, int totalRead, String attachmentPath)
throws IOException {
File file = new File(attachmentPath + tempAttachmentFileName);
byte[] b = new byte[totalRead - 2];
RandomAccessFile rafRead = new RandomAccessFile(file, "r");
rafRead.readFully(b, 0, totalRead - 2);
rafRead.close();
file.delete();
RandomAccessFile rafWrite = new RandomAccessFile(attachmentPath
+ fileName, "rw");
rafWrite.write(b);
rafWrite.close();
}
如有疑问 请留言 欢迎提供建议
评论已有 0 条