一、说明
文件上传与下载的路径我觉得就按照我写的就可以,如下: 
关于file文件夹,不需要我们手动建立,如下: 
因为每一个文件的名称不能保证唯一(因为不同的用户可能会上传相同的文件名的文件),为了保证重名的问题,我为每一个文件建立一个文件夹,文件夹饿名字通过UUID获取。  UUIDUtil工具类:
public class UUIDUtil {
public static String getID(){
return UUID.randomUUID().toString().replace("-", "");
}
}
二、文件上传(固定,代码是死的)
CommonsMultipartFile file:SpringMVC提供的文件上传下载类
@RequestMapping("/upload")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
String uploadFilename = file.getOriginalFilename();
if ("".equals(uploadFilename.trim())){
return "redirect:/index.jsp";
}
String path = request.getSession().getServletContext().getRealPath("file");
File realOfFile = new File(path);
if(!realOfFile.exists()){
realOfFile.mkdir();
}
System.out.println("file的相对路径==》"+realOfFile);
InputStream fileInputStream = file.getInputStream();
String uuidDirectory = UUIDUtil.getID();
new File(realOfFile+"/"+uuidDirectory).mkdir();
FileOutputStream fileOutputStream = new FileOutputStream(new File(realOfFile+"/"+uuidDirectory, uploadFilename));
int len = 0;
byte[] buffer = new byte[1024];
try{
while ((len=fileInputStream.read(buffer)) != -1){
fileOutputStream.write(buffer,0,len);
fileOutputStream.flush();
}
}catch (Exception e){
e.printStackTrace();
}finally {
fileInputStream.close();
fileOutputStream.close();
}
return "redirect:/index.jsp";
}
 
三、文件下载(固定,代码是死的)
String filePath:文件路径
@RequestMapping("/download")
public String fileDownload(@RequestParam("filePath") String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
String directoryName = request.getSession().getServletContext().getRealPath("file/");
String fileName = filePath.substring(filePath.lastIndexOf("/")+1);
response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(fileName,"utf-8"));
File file = new File(directoryName+filePath);
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream fileOutputStream = response.getOutputStream();
int len = 0;
byte[] buffer = new byte[1024];
try{
while ((len=fileInputStream.read(buffer)) != -1){
fileOutputStream.write(buffer,0,len);
fileOutputStream.flush();
}
}catch (Exception e){
e.printStackTrace();
}finally {
fileInputStream.close();
fileOutputStream.close();
}
return null;
}

|