ajax下载文件
@RequestMapping(value=”downLoad”)
public void downLoad(HttpServletRequest req,HttpServletResponse response) throws IOException{
//System.out.println(req.getParameter(“id”));
File file = new File(SHOT_PDF_PATH+this.getFileName());
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(this.getFileName(), "UTF-8"));
response.setContentType("applicationf");
while (fis.read(buffer) > 0) {
response.getOutputStream().write(buffer);
}
}
文件写入
:
public void upload(){
log.debug("[upload starts]");
BufferedOutputStream bos=null;
BufferedInputStream bis=null;
String newFileName=null;
try {
//得到当前时间开始流逝的毫秒数,将这个毫秒数作为上传文件新的文件名
long now=new Date().getTime();
//得到保存上传文件的真实路径
String path = context.getRealPath("../coursedoc/report/");
log.debug("4============================" + path);
File dir = new File(path);
//如果这个目录不存在,则创建它
if (!dir.exists()) {
dir.mkdirs();
}
int index = uploadifyFileName.lastIndexOf(".");
//判断上传文件是否有扩展名,以时间戳作为新的文件名
if (index!=-1) {
newFileName= now + uploadifyFileName.substring(index);
}else {
newFileName = Long.toString(now);
}
//读取保存在临时目录下的上传文件,写入到新的文件中
FileInputStream fis=new FileInputStream(uploadify);
bis=new BufferedInputStream(fis);
FileOutputStream fos=new FileOutputStream(new File(dir,newFileName));
bos=new BufferedOutputStream(fos);
byte [] buf=new byte[4096];
int len=-1;
while ((len=bis.read(buf))!=-1) {
bos.write(buf,0,len);
}
int reportId = this.submitReport(this.getSenderId(), this.getSecToken(), newFileName, this.getCourseId(), this.getAssignmentId(), this.getDesc());
}catch(Exception e){
e.printStackTrace();
}finally{
if (null!=bis) {
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (null!=bos) {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
resp.writeJson(response, newFileName);
log.debug("[submitPaper] responseData:" + responseData);
}