import com.zqf.common.exception.ToUserException;
import com.zqf.common.utils.ServletUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
- @auth
**/
@Controller
@RequestMapping("/upload")
public class FileController {
@RequestMapping(value = "/load",method = RequestMethod.POST)
public void upload(HttpServletRequest req,HttpServletResponse res,@RequestParam("file") MultipartFile file){
if(file.isEmpty()){
throw new ToUserException("上传文件为空!");
}
Long time = System.currentTimeMillis();
try {
String orginateFileName = new String(file.getOriginalFilename().getBytes("ISO-8859-1"),"UTF-8");
System.out.println("导入原始文件名:"+orginateFileName);
System.out.println("导入原始文件大小:"+file.getSize());
String fileName = time+"_"+orginateFileName;
File localFile = new File("D://"+fileName);
file.transferTo(localFile);
ServletUtils.toJson(fileName,req,res);
} catch (Exception e) {
e.printStackTrace();
}
}
@GetMapping("/downLoad")
public void download(String id, HttpServletRequest request, HttpServletResponse response) {
System.out.println(id);
try (
FileInputStream inputStream = new FileInputStream(new File("D://"+id));
ServletOutputStream outputStream = response.getOutputStream();
) {
// 声明响应类型
response.setContentType("application/x-download");
// 下载的文件名称
response.addHeader("Content-Disposition", "attachment;filename="+id);
IOUtils.copy(inputStream, outputStream);
//ServletUtils.toJson(request,response);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
网友评论