文件上传代码:
/**
*
* @Title: uploadFile
* @Description: 文件上传
* @param path 文件保存的路径,例:D:/upload/20101010/test.txt
* @param fileInputStream
* @return boolean
* @throws IOException
*
*/
public synchronized boolean uploadFile(String path,InputStream fileInputStream) throws IOException{
boolean result = false;
if(path!=null && path!=""){
FileOutputStream fos = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
try {
path = path.replaceAll("//","/");
String dirs[] = path.split("/");
String diretoryUrl = dirs[0];
//循环遍历路径的文件夹(除盘符外),如果没有文件夹则创建
for(int i=1; i<dirs.length-1; i++){
diretoryUrl = diretoryUrl + "/" + dirs[i];
File fileTemp = new File(diretoryUrl);
if(!fileTemp.exists()){
fileTemp.mkdirs();
}
}
File file = new File(path);
file.createNewFile();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bis = new BufferedInputStream(fileInputStream);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally{
if(bis!=null){
bis.close();
}
if(bos!=null){
bos.close();
}
if(fos!=null){
fos.close();
}
}
}
return result;
}
文件下载:
@RequestMapping(value="download", method=RequestMethod.GET)
public void download(String fileUrl, HttpServletRequest request, HttpServletResponse response) throws Exception{
String path= SAVE_URL + fileUrl;
System.out.println(path);
File file = new File(path);
if (!file.isFile()){
throw new Exception("要下载或打开的文件不存在!");
}
BufferedInputStream br = null;
OutputStream out = null;
try {
String name = file.getName();
String fileName = new String(name.getBytes("GBK"),"ISO8859-1");
br = new BufferedInputStream(new FileInputStream(file));
Integer size = br.available();
byte[] buf = new byte[2048];
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/octet-stream; charset=utf-8");
response.addHeader("Content-Length", "" + size);
out = response.getOutputStream();
int len = 0;
while ((len = br.read(buf)) != -1) {
out.write(buf, 0, len);
}
} catch (Exception e){
e.printStackTrace();
} finally {
if (br != null){
br.close();
}
if (out != null){
out.close();
}
}
}