js根据本地文件路径上传文件(流上传)
生活随笔
收集整理的這篇文章主要介紹了
js根据本地文件路径上传文件(流上传)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
最近使用vue做了個項目,把本地指定url下的png圖片上傳。
廢話不多說,直接上代碼:
var fs = require('fs') //需要引入nodejs中的文件操作部分 var http = require('http') //需要引入nodejs中http請求部分 /*** 實際封裝接口的入口* @param {*} options 請求的配置項* @param {*} path 文件上傳路徑* @param {*} id 文件上傳參數(shù)(id)* @param {*} name 文件上傳參數(shù)(name)* @param {*} token 接口上傳使用的token* @param {*} cb 上傳成功后的回調(diào)函數(shù)* @param {*} errCb 上傳失敗后的回調(diào)*/ function uploadFile(options, path, id, name, token, cb, errCb){var req = http.request(options, (res)=>{ // console.log("RES:" + res); // console.log('STATUS: ' + res.statusCode); // console.log('HEADERS: ' + JSON.stringify(res.headers));res.on("data", (chunk)=>{console.log("BODY:" + chunk);if(typeof cb == 'function'){ //如果請求成功返回,執(zhí)行成功回調(diào)函數(shù)cb(JSON.parse(chunk.toString())); //將結(jié)果返回,返回結(jié)果是json格式的情況下JSON.parse解析下再返回}})})req.on('error', (e)=>{if(typeof errCb == 'function'){ //如果請求失敗后,執(zhí)行失敗回調(diào)函數(shù)errCb(e.toString()); //將結(jié)果返回}})postFile([{urlKey: "file", urlValue: path}], req, id, name, token); }function postFile(fileKeyValue, req, id, name, token) {var boundaryKey = Math.random().toString(16);var enddata = '\r\n----' + boundaryKey + '--';var files = new Array();for (var i = 0; i < fileKeyValue.length; i++) {var content = ''; // "\r\n----" + boundaryKey + "\r\n" + "Content-Type: image/jpeg\r\n" + "Content-Disposition: form-data; name=\"" + fileKeyValue[i].urlKey + "\"; filename=\"" + (fileKeyValue[i].urlValue) + "\"\r\n" + "Content-Transfer-Encoding: binary\r\n\r\n";var contentBinary = new Buffer.from(content, 'utf-8');//當(dāng)編碼為ascii時,中文會亂碼。files.push({contentBinary: contentBinary, filePath: fileKeyValue[i].urlValue});}var contentLength = 0;for (var i = 0; i < files.length; i++) {var stat = fs.statSync(files[i].filePath);contentLength += files[i].contentBinary.length;contentLength += stat.size;}//請求參數(shù)放到了header頭中,后臺從header中取req.setHeader('token', token);req.setHeader('id', id);req.setHeader('name', name);// req.setHeader('Content-Type', 'multipart/form-data; boundary=--' + boundaryKey);//這里暫時不設(shè)置,瀏覽器會根據(jù)實際上傳文件自動識別,如果不行再設(shè)置req.setHeader('Content-Type', 'text/html; charset=UTF-8');req.setHeader('Content-Length', contentLength + Buffer.byteLength(enddata)); // 將參數(shù)發(fā)出var fileindex = 0;var doOneFile = function(){req.write(files[fileindex].contentBinary);var fileStream = fs.createReadStream(files[fileindex].filePath, {bufferSize : 4 * 1024});fileStream.pipe(req, {end: false});fileStream.on('end', function() {fileindex++;if(fileindex == files.length){req.end(enddata);} else {doOneFile();}});};if(fileindex == files.length){req.end(enddata);} else {doOneFile();} }函數(shù)的調(diào)用如下:
let options = { host: that.$servletUri, //例如:127.0.0.1 不需加http://...port: that.$servletPort, //例如:8080method: "POST", path: '/api/fileupload', //流上傳方法名}let fileName = Date.parse(new Date());// 該封裝方法放入了utils工具類中,所以這里用this.$util.this.$util.uploadFile(options, fileUrl, that.currentRowId, fileName, this.$store.state.userInfo.token,(res)=>{// 上傳成功后執(zhí)行的方法if(res.code == 1){this.$message('截圖上傳成功!')}},(err)=>{this.$message.error('截圖上傳失敗,請稍后重試!');});再貼一下后臺代碼:
controller:
@PostMapping("/fileupload")public Response uploadFile(HttpServletRequest request, HttpServletResponse response,Integer id,String fileName) throws Exception{//String fileName = "hh.png";//request.getParameter("fileName");return documentService.uploadFile(request);}service:
Response uploadFile(HttpServletRequest request);serviceImpl:
// // 下面fileUpload這里對應(yīng)yml文件中配置服務(wù)器保存的路徑 // // file: // fileUpload: /home/work/java/images/ // @Value("${file.fileUpload}") private String fileUpload;@Override public Response uploadFile(HttpServletRequest request) {Integer id = 0;if (null != request.getHeader("id")){id = Integer.parseInt(request.getHeader("id"));}String fileName1 =request.getHeader("name")+".png";String dirPath =fileUpload+id;//會在webapp下面創(chuàng)建此文件夾String fileFullPath = dirPath+System.getProperty("file.separator")+ fileName1;InputStream input = null;FileOutputStream fos = null;try {input = request.getInputStream();File file = new File(dirPath);if(!file.exists()){file.mkdirs();}fos = new FileOutputStream(fileFullPath);byte[] buffer = new byte[1024];/* int size = 0;byte[] buffer = new byte[4*1024];while ((size = input.read(buffer,0,4*1024)) != -1) {fos.write(buffer, 0, size);}*/int length = 0;do {length = input.read(buffer);if (length > 0) {fos.write(buffer, 0, length);}} while (length>0);} catch (IOException e) {e.printStackTrace();return Response.successErr("操作失敗");} finally{if(input != null){try {input.close();} catch (IOException e) {e.printStackTrace();}}if(fos != null){try {fos.close();} catch (IOException e) {e.printStackTrace();}}} }總結(jié)
以上是生活随笔為你收集整理的js根据本地文件路径上传文件(流上传)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【笔记17】使用 jad 工具把 jav
- 下一篇: 滴滴是如何搭建起PB级数据中台的?