ttms-9
1.文件上传业务分析?
1)将文件上传到服务器,然后存储到服务器的某个位置.
2)将已上传的文件相关信息存储到数据库.例如文件名,
文件大小,文件摘要信息,文件在服务器上的地址等.
2.SSM架构中文件上传的实现?
1)添加文件上传依赖?
2)spring-mvc中添加文件上传解析配制?
3)设置文件上传表单。
4)Spring controller中数据的接收?
在spring中可以借助此MultipartFile类型
的对象接收页面表单中上传的数据.
实现文件上传
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import cn.tedu.ttms.attachment.dao.AttachmentDao;
import cn.tedu.ttms.attachment.entity.Attachment;
import cn.tedu.ttms.attachment.service.AttachmentService;
import cn.tedu.ttms.common.exception.ServiceException;
@Service
public class AttachmentServiceImpl implements AttachmentService {
@Autowired
private AttachmentDao attachmentDao;
@Override
public Attachment findObjectById(Integer id) {
if(id==null)
throw new ServiceException("id不能为空");
Attachment a=attachmentDao.findObjectById(id);
if(a==null)
throw new ServiceException("对象已经不存在");
return a;
}
@Override
public void saveOject(String title,
MultipartFile mFile) {
if(StringUtils.isEmpty(title))
throw new ServiceException("title 不能为空");
if(mFile==null)
throw new ServiceException("请选择上传文件");
if(mFile.isEmpty())
throw new ServiceException("不允许上传空文件");
String digest=null;
try{
byte []bytes=mFile.getBytes();
digest=
DigestUtils.md5DigestAsHex(bytes);
}catch(Exception e){
e.printStackTrace();
throw new ServiceException("文件上传失败");
}
int count=
attachmentDao.getRowCountByDigest(digest);
if(count>0)
throw new ServiceException("文件已经上传");
SimpleDateFormat sdf=
new SimpleDateFormat("yyyy/MM/dd");
String dateDir=sdf.format(new Date());
File fileDir=new File("e:/uploads/"+dateDir);
if(!fileDir.exists())fileDir.mkdirs();
File dest=new File(fileDir,
mFile.getOriginalFilename());
try{
mFile.transferTo(dest);
}catch(Exception e){
e.printStackTrace();
throw new ServiceException("文件上传失败");
}
Attachment a=new Attachment();
a.setTitle(title);
a.setFileName(mFile.getOriginalFilename());
a.setFileDisgest(digest);
a.setFilePath(dest.getPath());
a.setContentType(mFile.getContentType());
int rows=attachmentDao.insertObject(a);
if(rows<=0)
throw new ServiceException("数据保存失败");
}
@Override
public List<Attachment> findObjects() {
return attachmentDao.findObjects();
}
}
Spring中文件的下载 a
1.设置下载时的响应头(必须设置,固定格式)
response.setContentType("application/octet-stream");
File fileName=new String(fileName.getBytes("iso-8859-1"),"utf-8");
中文文件名可能有乱码,通过如下语句对文件名编码
String fileName=URLEncoder.encode(
a.getFileName(),"utf-8");
response.setHeader("Content-disposition",
"attachment;filename="+fileName);
2.返回要下载数据,交给浏览器下载
根据文件路径构建一个Path
Path path=Paths.get(a.getFilePath());
读取指定路径下的文件字节
return Files.readAllBytes(path);