微信小程序上傳文件Java后台實現


微信小程序上傳文件

開發環境:微信開發者工具+eclipse+Tomcat+Mysql

1、過程描述

Mysql中存放的是文檔的記錄(如文檔名、存放的地址等),而不是文檔中實際的內容。
文檔實際存放在本地磁盤的某個文件夾中
微信開發者工具提供接口,訪問eclipse中的Java項目地址,在對應的Java項目中將讀到的內容寫入磁盤。

2、代碼

前台

.wxml

<form bindsubmit="submit"> <view> <input placeholder='請輸入文件名,如:張三-論文' name="fileName" /> <view class='button'> <button type='primary' form-type='submit'>確定</button> </view> </view> <view class="br"></view> <view class="weui-uploader__input-box"> <view class="weui-uploader__input" bindtap="upload"></view> </view> </form>

.js
var account; var fileName; Page({ data: { files: [] }, submit:function(e){ var objData = e.detail.value; fileName=objData.fileName; if (fileName==''){ wx.showToast({ title: '請輸入文件名', duration: 2000, }) } }, upload: function(e) { if(fileName==''){ wx.showToast({ title: '請輸入文件名', }) } if (fileName == ''||fileName == undefined) { wx.showToast({ title: '請確定', }) } else{ var account = wx.getStorageSync('account'); var that = this; wx.chooseMessageFile({ count: 10, type: 'file', success(res) { wx.uploadFile({ url: 'http://192.168.x.xxx:8080/GraduateDesign/StuUploadPaper', filePath: res.tempFiles[0].path, name: 'file', header: { 'content-type': 'multipart/form-data' }, formData:{ fileName:fileName, account:account }, success(res) { if(res.data==1) wx.showToast({ title: '上傳成功', }) else{ wx.showToast({ title: '文件已存在', }) } } }) } }) } } })

.json

{ "navigationBarTitleText": "提交論文" }

.wxss

input{ border: 1px solid #ccc; height: 40px; margin-left: 10px; margin-right: 10px; } .button{ margin-top: 10px; margin-left: 10px; } .weui-uploader__input-box{ margin-bottom: 40px; margin-left: 100px; width:120px; height: 120px; } .br{ width: 20px; height: 20px; }
后台

(只貼了關鍵部分)

package GraduateDesign.servlet; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Writer; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import GraduateDesign.domain.StuFile; import GraduateDesign.service.StuFileService; public class StuUploadPaper extends HttpServlet { private static final long serialVersionUID = 1L; public StuUploadPaper() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "GET,POST"); String fname=null; //前台傳過來的文件名(不帶后綴) String account=null; //教師工號 String value=null; //前台傳的formdata中的值,有兩個:file、account,要遍歷取出 String fileName=null; //最終的文件名稱(帶后綴) String destPath=null; //上傳的文件的完整地址 String path ="D:/eclipse-workspace/GraduateDesign/WebContent/WEB-INF/paper"; //這是我在磁盤上存放文件的地址 File dir = new File(path); /*如果指定目錄不存在就創建*/ if (!dir.exists()) { dir.mkdir(); } DiskFileItemFactory factory=new DiskFileItemFactory(); factory.setRepository(dir); //設置緩存的大小,當上傳文件的容量超過該緩存時,直接放到暫時存儲室 factory.setSizeThreshold(1024 * 1024); //高水平的API文件上傳處理 ServletFileUpload upload=new ServletFileUpload(factory); upload.setHeaderEncoding("utf-8");//解決前台傳過來的值亂碼問題 try { List<FileItem> list=upload.parseRequest(request); FileItem file=null; for(FileItem item : list){ if (item.isFormField()) { //獲取用戶具體輸入的字符串,分別取出文件名fname和學生學號account value = item.getString("utf-8"); if(fname==null){ fname=value; continue; } if(account==null){ account=value; } } else { file = item; } } fileName = account+"-"+fname + ".doc"; destPath = path + "/" + fileName; //真正寫到磁盤上 //System.out.println(destPath); File f = new File(destPath); OutputStream out = new FileOutputStream(f); InputStream in = file.getInputStream(); int length = 0; byte[] buf = new byte[1024]; // in.read(buf) 每次讀到的數據存放在buf 數組中 while ((length = in.read(buf)) != -1) { //在buf數組中取出數據寫到(輸出流)磁盤上 out.write(buf, 0, length); } in.close(); out.close(); } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } /*更新數據庫中記錄*/ Date date=new Date(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); String time=df.format(date); StuFile sf=new StuFile(); sf.setFileName(fileName); sf.setFileUrl(destPath); sf.setSno(account); sf.setDate(time); StuFileService sfs=new StuFileService(); boolean b=sfs.upload(sf); /*向前台返回是否成功標志位*/ String flag; if(b==true) flag="1"; else flag="0"; Writer out = response.getWriter(); out.write(flag); out.flush(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

3、運行結果

在這里插入圖片描述

在這里插入圖片描述
在這里插入圖片描述

數據庫中記錄在這里插入圖片描述
本地磁盤記錄

附:
兩個jar包(io包、fileupload包),百度網盤https://pan.baidu.com/s/1-xdFZSsCJo7Ai3f
提取碼:8mvg


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM