中山专业网站建设模板代理,镇江互联网公司,wordpress首页加广告,回收那个网站做推广好1.文件上传
文件上传#xff0c;也称为upload#xff0c;是指将本地图片、视频、音频等文件上传到服务器上#xff0c;可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛#xff0c;我们经常发微博、发微信朋友圈都用到了文件上传功能。 import com.itheima.…1.文件上传
文件上传也称为upload是指将本地图片、视频、音频等文件上传到服务器上可以供其他用户浏览或下载的过程。文件上传在项目中应用非常广泛我们经常发微博、发微信朋友圈都用到了文件上传功能。 import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
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 java.io.File;
import java.util.UUID;/*** 文件上传和下载*/
Slf4j
RequestMapping(common)
RestController
public class CommonController {private String basePath;/*** 文件上传*/PostMapping(upload)public RString upload(MultipartFile file) throws Exception {//file是一个临时文件需要转存到指定位置否则本次请求完成后临时文件会删除log.info(file.toString());//创建一个目录对象File dir new File(basePath);//basePathd:/img///判断当前目录是否存在if (!dir.exists()) {//目录不存在需要创建dir.mkdirs();}//原始文件名String originalFilename file.getOriginalFilename();//abc.jpg//原始文件名后缀 .jpgString suffix originalFilename.substring(originalFilename.lastIndexOf(.));//使用UUID重新生成文件名防止文件名称重复造成文件覆盖String fileName UUID.randomUUID().toString() suffix;//dfsdfdfd.jpg//将临时文件转存到指定位置file.transferTo(new File(basePath fileName));d:/img/dfsdfdfd.jpgreturn R.success(basePath fileName);}
} 2.文件下载
文件下载也称为download是指将文件从服务器传输到本地计算机的过程。 下面的下载文件的代码是 直接把文件通过response 设置好响应头,直接返回给浏览器, (后端代码完成的)
然后浏览器自己根据response的响应头的参数去判断此文件是什么类型的,然后再去解析然后进行页面下载.(浏览器自己处理的)
RestController
RequestMapping(aa)
public class ExecleController {/*** param outputDir 要下载的文件的绝对路径* param response HttpServletResponse* throws IOException*/public void filedown(String outputDir, HttpServletResponse response) throws IOException {String downName 给下载的文件取个名字;File file null;FileInputStream is null;try {response.setContentType(text/html;charsetutf-8);response.setCharacterEncoding(UTF-8);response.setHeader(content-disposition, attachment;filename\ URLEncoder.encode(downName, utf-8) \);file new File(outputDir);new FileInputStream(file);ServletOutputStream os response.getOutputStream();IOUtils.copy(is, os);} catch (IOException e) {e.printStackTrace();} finally {if (is ! null) {is.close();}if (file ! null) {file.delete();}}}
}