上海网站制作开发公司,万互网站建站,如何建立网站建设,商务网站建设的必备功能上传文件#xff1a;
前端#xff1a;
整个过程#xff0c;就是在使用FormData 添加 上File#xff08;这个Blob#xff09;#xff0c;并且key要和后台的名字对应上在点击上传按钮开始上传之前#xff0c;使用了URL.createObjectURL(File)创建blobUrl#xff0c;给了…上传文件
前端
整个过程就是在使用FormData 添加 上File这个Blob并且key要和后台的名字对应上在点击上传按钮开始上传之前使用了URL.createObjectURL(File)创建blobUrl给了img标签作图片预览上传完毕后将input file的value置为空。若将input file置为空则此时不能再从input file中获取file了得等下次再选择图片才能获得file将它置为空的目的是为了下次选择同样的图片也能触发input file的change事件
后端
后台仅仅就是用MultipartFile声明接收即可可以使用RequestParam注解 或 RequestPart注解调用MultipartFile#transferTo保存文件可以从MultipartFile#getInputStream中获取流比如上传到OSS。 前端代码
templatediv选择文件: input typefile reffileInputRef changeselectFile multiple !-- 使用multiple属性,可选择多个文件 --br/img v-ifimgUrl :srcimgUrl alt stylewidth:54px;height:54px;el-button v-ifimgUrl typeprimary clickuploadFile上传/el-buttonhr//div
/templatescript
import axiosInstance from /utils/request.js
import axios from axios
export default {name: File,data() {return {imgUrl:}},methods: {selectFile() {let file this.$refs[fileInputRef].files[0]console.log(file)// 上传前, 可以预览该图片let blobUrl URL.createObjectURL(file)this.imgUrl blobUrl},uploadFile() {// 因为可能选择多个文件, 所以这里是个数组let file this.$refs[fileInputRef].files[0]let formData new FormData()formData.append(mfile, file) // 必须和后端的参数名相同。我们看到了, 其实就是把blob文件给了formData的一个keyformData.append(type, avatar)// 可以有下面2种方式, 来上传文件/* axiosInstance.post(http://127.0.0.1:8083/file/uploadFile,formData, {headers: {a:b}}).then(res {console.log(响应回来: ,res);}) */axiosInstance({ // 这种传参方式, 在axios的index.d.ts中可以看到url:http://127.0.0.1:8083/file/uploadFile,method:post,data: formData, // 直接将FormData作为data传输headers: {a:b // 可携带自定义响应头}}).then(res {console.log(响应回来: ,res);})console.log(this.$refs[fileInputRef].value); // C:\fakepath\cfa86972-07a1-4527-8b8a-1991715ebbfe.png// 上传完文件后, 将value置为空, 以避免下次选择同样的图片而不会触发input file的change事件。// (注意清空value后将不能再从input file中获取file而原先的file仍然能够使用)this.$refs[fileInputRef].value }}
}
/scriptstyle/style后端代码
PostMapping(uploadFile)
public Object uploadFile(RequestPart(mfile)MultipartFile multipartFile,RequestPart(type) String type) throws IOException {System.out.println(multipartFile.getClass());System.out.println(type);// 源文件名String originalFilename multipartFile.getOriginalFilename();// 内容类型String contentType multipartFile.getContentType();// 文件是否为空无内容boolean empty multipartFile.isEmpty();// 文件大小long size multipartFile.getSize();// 文件的字节数据byte[] bytes multipartFile.getBytes();// 获取文件的字节输入流InputStream inputStream multipartFile.getInputStream();// 将文件保存到指定路径下multipartFile.transferTo(new File(d:/Projects/practice/test-springboot/src/main/resources/file/ originalFilename));System.out.println(originalFilename);System.out.println(contentType);System.out.println(empty);System.out.println(size);System.out.println(bytes.length);HashMapString, Object data new HashMap();data.put(data, ok);return data;
}动态a标签下载
前端代码
只需要动态创建a标签添加到body然后手动调用js触发a标签的click事件触发下载下载完成之后将a标签移除整个过程a标签的样式都是display:none
templatedivel-button typesuccess clickdownloadFile下载文件/el-button/div
/templatescript
import axiosInstance from /utils/request.js
import axios from axios
export default {name: File,data() {return {}},methods: {downloadFile() {let a document.createElement(a)a.href http://127.0.0.1:8083/file/downloadFile?filename头像a.pngdocument.body.appendChild(a)a.style.display nonea.click()document.body.removeChild(a)}}
}
/scriptstyle/style后端代码
GetMapping(downloadFile)
public void downloadFile(RequestParam(filename) String filename) throws Exception {// 告知浏览器这是一个字节流浏览器处理字节流的默认方式就是下载// 意思是未知的应用程序文件浏览器一般不会自动执行或询问执行。浏览器会像对待// 设置了HTTP头Content-Disposition值为attachment的文件一样来对待这类文件即浏览器会触发下载行为response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);// ,该响应头指示回复的内容该以何种形式展示是以内联的形式即网页或者网页的一部分还是以附件的形式下载并保存到本地。response.setHeader(HttpHeaders.CONTENT_DISPOSITION,attachment;fileName URLEncoder.encode(filename, UTF-8));File file new File(d:/Projects/practice/test-springboot/src/main/resources/file/ filename);ServletOutputStream ros response.getOutputStream();FileInputStream fis new FileInputStream(file);byte[] bytes new byte[2 * 1024];int len 0;while ((len fis.read(bytes)) ! -1) {ros.write(bytes, 0, len);}ros.flush();ros.close();fis.close()}预览文件
前端代码
templatediva hrefhttp://127.0.0.1:8083/file/previewFile?filename头像a.png头像a.png/a/div
/templatescript
import axios from axios
export default {name: File,data() {return {}},methods: {}
}
/scriptstyle/style后端代码
GetMapping(previewFile)public void previewFile(RequestParam(filename) String filename) throws Exception {// 可使用ServletContext 通过文件名获取 媒体资源类型response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE);File file new File(d:/Projects/practice/test-springboot/src/main/resources/file/ filename);ServletOutputStream ros response.getOutputStream();// 可参考: StreamUtilsFileInputStream fis new FileInputStream(file);byte[] bytes new byte[4 * 1024];int len 0;while ((len fis.read(bytes)) ! -1) {ros.write(bytes, 0, len);}ros.flush();ros.close();fis.close()
}