图片/文件上传与下载
文件下载
@RequestMapping("downFile")
public void download(String attachmentNo, HttpServletResponse response) {
try {
//查询实体
CollectAttachment att = service.get(CollectAttachment.class, attachmentNo);
// path是指欲下载的文件的路径。
File file = new File(att.getS_attachmentUrl());
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(att.getS_attachmentUrl()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
String realyFileName = "";
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") >0){
realyFileName = new String(att.getS_fileName().getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=\"" + realyFileName+ "\"");
}else{
realyFileName = URLEncoder.encode(att.getS_fileName(), "UTF-8");//IE浏览器
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + realyFileName);
}
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
// 写入
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
图片下载
@RequestMapping("downLoad")
public void downLoad(String downId) throws UnsupportedEncodingException{
CollImageinfo imageinfo=maintainService.get(CollImageinfo.class, downId);
String filename=imageinfo.getS_dataUrl();
// 获得文件流,输出到response的输出流中
String file=ServletUtil.getServletContext().getRealPath(filename);
File f=new File(file);
if(f.exists()){
// 配置响应头,使之成为下载
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentType("application/x-download");
FileInputStream fs=null;
OutputStream os=null;
try {
fs=new FileInputStream(f);
os=response.getOutputStream();
byte[] bt=new byte[1024];
while(fs.read(bt)!=-1){
os.write(bt);
}
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(fs!=null){
fs.close();
}
if(os!=null){
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}else {
System.out.println("你下载的文件不存在");
}
}
图片预览上传(jsp页面)
<div>
<input id="avatarSlect" type="file" name="file" style="position: absolute;float: left; z-index: 10; opacity: 0;width: 80px; height: 120px;" onchange="checkfm()">
<img id="avatarPreview" src="${webRoot}/resource/images/portrait/timg/timg.jpg" title="点击更换图片" style="position: absolute; z-index: 9; float: left; width: 90px; height: 100px">
</div>
<script>
$(function () {
bindAvatar2();
});
function bindAvatar2() {
console.log(2);
$("#avatarSlect").change(function () {
var obj=$("#avatarSlect")[0].files[0];
var fr=new FileReader();
fr.onload=function () {
$("#avatarPreview").attr('src',this.result);
console.log(this.result);
$("#avatar").val(this.result);
};
fr.readAsDataURL(obj);
})
}
function checkfm(){
var avatarSlect = $("#avatarSlect").val();
if(avatarSlect!=""){
var types = ["jpg","jpeg","gif","png","bmp"];
var ext = avatarSlect.substring(avatarSlect.length-3).toLowerCase();
var sing = false;
for(var i=0; i<types.length;i++){
if (ext==types[i]){
sing = true;
}
}
if(!sing){
Msg.alert('提示', '请选择图片!');
$("#avatarSlect").val("");
return false;
}
}
return true;
}
</script>
图片上传(上传到项目中)
在Java中接受MultipartFile fileNames
//地址前生成随机数
public static UUID randomUUID() {
SecureRandom ng = Holder.numberGenerator;
byte[] randomBytes = new byte[16];
ng.nextBytes(randomBytes);
randomBytes[6] &= 0x0f; /* clear version */
randomBytes[6] |= 0x40; /* set to version 4 */
randomBytes[8] &= 0x3f; /* clear variant */
randomBytes[8] |= 0x80; /* set to IETF variant */
return new UUID(randomBytes);
}
String nowFileName = UUID.randomUUID()+"";
String uploadDir=session.getServletContext().getRealPath("/upload/"+nowFileName+fileNames.getOriginalFilename());
File file=new File(uploadDir);
if(!file.exists()) {
file.mkdirs();
}
fileNames.transferTo(file);
String filenames="upload/"+nowFileName+fileNames.getOriginalFilename();
imageInfo.setS_dataUrl(filenames);
添加附件
@Override
public boolean addAttachment(String type, String dataNo, FileList files,String[] theme) {
// TODO Auto-generated method stub
// 通过文件列表获取上传文件
List<MultipartFile> fileList = files.getFile();
//判断是否有文件
if (fileList != null) {
int count = 0;
//循环遍历文件
for (MultipartFile f : fileList) {
//如果文件不为空
if (f != null && !f.isEmpty()) {
// Date date = new Date();
//使用时间戳作为名字
String nowFileName = UUID.randomUUID()+"";
String ext = FileUtils.getFileExt(f.getOriginalFilename());// 获取文件后缀
//判断目录是否存在
File filePath = new File(SAVEPATH);
if(!filePath.exists()){
filePath.mkdirs();
}
// 保存文件
File newFile = new File(SAVEPATH + "/" + nowFileName + "." + ext);
try {
//转换为文件
f.transferTo(newFile);
//创建模型对象
CollectAttachment at = new CollectAttachment();
//设置创建时间
at.setD_createTime(DateUtil.getNowDate());
//设置文件名称
if(theme.length>0 && !"".equals(theme[count])){
at.setS_theme(theme[count]);
}else{
at.setS_theme(FileUtils.getFileName(f.getOriginalFilename()));
}
at.setS_fileName(f.getOriginalFilename());
//设置文件路径
at.setS_attachmentUrl(SAVEPATH + "/" + nowFileName + "." + ext);
//设置业务记录编号
at.setS_dataNo(dataNo);
//设置附件类型
at.setS_type(type);
//设置创建人员
at.setS_createUser("系统管理员");
dao.save(at);
count++;
} catch (IllegalStateException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}
}
}
return true;
}