import com.rome.backend.common.R; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.UUID; /** * 文件上传下载 */ @RestController @RequestMapping("/common") public class CommonController { /** * 上传 * @param file * @return */ @PostMapping("/upload") public R<String> upload(MultipartFile file){//参数名和前端input名一样 //file是一个临时文件,需要转存到指定位置,否则本次请求完成后临时文件会删除 //获取当前项目路径进行拼接 String url = System.getProperty("user.dir")+"\\backend\\src\\main\\resources\\backend\\images\\dish\\dishload\\"; //使用uuid重新生成文件名防止文件名重复造成覆盖,uuid+原始文件名 String uuid = UUID.randomUUID().toString(); // uuid+原始文件名 String fileName = uuid.concat(file.getOriginalFilename()); // 将文件转存 try { file.transferTo(new File(url+fileName)); } catch (IOException e) { throw new RuntimeException(e); } return R.success(fileName); } /** * 下载 * @param name * @param response */ @GetMapping("/download") public void download(String name, HttpServletResponse response){ //图片路径 String urlImg = System.getProperty("user.dir")+"\\backend\\src\\main\\resources\\backend\\images\\dish\\dishload\\".concat(name); try { //通过输入流读取文件内容 FileInputStream fileInputStream = new FileInputStream(new File(urlImg)); //输出流到浏览器 ServletOutputStream outputStream = response.getOutputStream(); //设置响应回去的是什么类型的文件 response.setContentType("image/jpeg"); int len = 0; byte[] bytes = new byte[1024]; while ((len = fileInputStream.read(bytes)) != -1){ outputStream.write(bytes,0,len); outputStream.flush(); } //关闭资源 outputStream.close(); fileInputStream.close(); } catch (Exception e) { e.printStackTrace(); } } }
标签:文件,uuid,web,springframework,new,import,上传,下载,String From: https://www.cnblogs.com/romablog/p/17280076.html