这段时间尝试写了一个小web项目,其中涉及到文件上传与下载,虽然网上有很多成熟的框架供使用,但为了学习我还是选择了自己编写相关的代码。当中遇到了很多问题,所以在此这分享完整的上传与下载代码供大家借鉴。
首先是上传的Servlet代码
[java]
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.util.Random;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpLoad extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Random RANDOM = new Random();
private String tempFileFolder; //临时文件存放目录
private String fileFolder; //存文件的目录
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//step 1 将上传文件流写入到临时文件
File tempFile = getTempFile();
writeToTempFile(request.getInputStream(), tempFile);
//step 2从临时文件中取得上传文件流
RandomAccessFile randomFile = new RandomAccessFile(tempFile, "r");
//step 3取得文件名称
String filename = getFileName(randomFile);
//step 4检查存放文件的目录在不在
checkFold();
//step 5保存文件
long fileSize = saveFile(randomFile, filename);
//step 6关闭流对像,删除临时文件
randomFile.close();
tempFile.delete();
}
public void init() throws ServletException {
//获取项目所在目录
String contentPath = getServletContext().getRealPath("/");
this.tempFileFolder = contentPath + "files/_tmp";
this.fileFolder = contentPath+"files/_file";
}
/**
* 对字符串进行转码
* @param str
* @return 转码后的字符串
*/
private String codeString(String str) {
String s = str;
try {
byte[] temp = s.getBytes("ISO-8859-1");
s = new String(temp, "UTF-8");
return s;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return s;
}
}
/**
* 产生临时文件对象
* 会检查临时目录是否存在,如果不存在将创建目录
* @return 临时文件对象
* @throws IOException
*/
private File getTempFile()throws IOException{
File tempFolder = new File(this.tempFileFolder);
if (!tempFolder.exists()){
tempFolder.mkdirs();
}
String tempFileName = this.tempFileFolder+File.separator+Math.abs(RANDOM.nextInt());
File tempFile = new File(tempFileName);
if (!tempFile.exists()){
tempFile.createNewFile();
}
return tempFile;
}
/**
* 将上传的数据流存入临时文件
* @param fileSourcel 上传流
* @param tempFile 临时文件
* @throws IOException
*/
private void writeToTempFile(InputStream fileSourcel,File tempFile)throws IOException{
FileOutputStream outputStream = new FileOutputStream(tempFile);
byte b[] = new byte[1000];
int n ;
while ((n=fileSourcel.read(b))!=-1){
outputStream.write(b,0,n);
}
outputStream.close();
fileSourcel.close();
}
/**
* 从临时文件流中提取文件名称
* @param randomFile
* @return 解析的文件名称
* @throws IOException
*/
private String getFileName(RandomAccessFile randomFile)th
补充:软件开发 , Java ,