1. 程式人生 > >小程式之檔案上傳

小程式之檔案上傳

小程式前端資料處理

// 引入Model類
import {PlayModel} from "../../../models/PlayModel";
import {FileModel} from "../../../models/FileModel";
import {TimeStorage} from "../../../utils/timeStorage";


let playModel = new PlayModel();
let fileModel = new FileModel();
let timeStorage = new TimeStorage();

Page({

  /**
   * 頁面的初始資料
   */
data: { // 詳情數 contentCount: 0, // 標題內容 content: '', // 圖片列表 images: [], // 視訊 video : '', }, // 表單提交事件 submitClick() { if (this.data.content == '') { wx.showToast({ title: '內容不能為空!', duration: 2000, icon: 'none', mask:true }
) } else if (this.data.images.length == 0 && this.data.video == '') { wx.showToast({ title: '視訊和圖片必須新增一個!', duration: 2000, icon: 'none', mask:true }) } else { let artContent = this.data.content; let userId = timeStorage.getStorage(
"userInfo").user.userId; wx.showToast({ title: '載入中...', mask: true, icon: 'loading' }) if(this.data.video == ''){ playModel.submitArticle({ data: { userId: userId, artContent: artContent, }, success: (res) => { let artId = res.object; // 多圖片上傳 this.data.images.map(function(value, index){ fileModel.uploadImages({ data: value, success: (res) => { playModel.submitImages({ data: { artId: artId, imgUrl: res.msg }, success: (res) => { console.log(res) } }) } }) }) wx.showToast({ title: '成功', icon: 'success', duration: 2000, success: function() { // 成功後返回上一頁 wx.navigateBack({delta:1}) } }) } }); }else{ // 視訊上傳 fileModel.uploadVideo({ data: this.data.video, success: (res) => { playModel.submitArticle({ data: { userId: userId, artVideo: res.msg, artContent: artContent, }, success: (res) => { if(res.code == '200'){ wx.showToast({ title: '成功', icon: 'success', duration: 2000, success: function() { // 成功後返回上一頁 wx.navigateBack({delta:1}) } }) }else{ wx.showToast({ title: '失敗', icon: 'none', duration: 2000 }) } } }); } }) } } } })

對圖片和視訊上傳的處理

import { FileUpload } from "../utils/fileUpload.js"

class FileModel extends FileUpload {

      // 視訊上傳
  uploadVideo(params) {
    this.request({
      url: 'article/uploadVideo',
      data: params.data,
      success: (res) => {
        params.success && params.success(res)
      }
    })
  }


  // 圖片上傳
  uploadImages(params) {
    this.request({
      url: 'article/uploadImage',
      data: params.data,
      success: (res) => {
        params.success && params.success(res)
      }
    })
  }

}

export { FileModel }

對圖片和視訊API上傳

import { config } from "../config.js"
import { tips } from "./error_code.js"

class FileUpload{

    request(params) {
        wx.uploadFile({
            url: config.api_local_url + params.url,
            filePath: params.data,
            name: 'file',
            success: (res) => {
                let code = res.statusCode.toString()
                if (code.startsWith("2")) {
                    params.success && params.success(JSON.parse(res.data))
                } else {
                    let error_code = res.data.error_code
                    this._error_status(error_code)
                }
            },
            fail: (error) => {
                this._error_status(1000)
            }
        })
    }

    _error_status(error_code) {
        wx.showToast({
          title: tips[error_code],
          icon: 'none',
          duration: 2000
        })
      }
}

export { FileUpload }

springboot後臺的處理

Controller處理

@RestController
@RequestMapping("/api")
public class ArticleAPI {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private ArticleImagesService imagesService;

    /**
     * @function 視訊上傳
     * @return
     */
    @PostMapping("/article/uploadVideo")
    public JsonResult uploadVideo(@RequestParam(value = "file", required = false) MultipartFile file) {
        if(file == null){
            return new JsonResult(ResultCode.FAIL, "內容為空");
        }else{
            return new JsonResult(ResultCode.SUCCESS, FileUpload.fileOne(file, UploadType.ARTICLE_VIDEO));
        }

    }

    /**
     * @function 圖片上傳
     * @param file
     * @return
     */
    @PostMapping("/article/uploadImage")
    public JsonResult uploadImages(@RequestParam(value = "file", required = false) MultipartFile file) {
        if(file == null) {
            return new JsonResult(ResultCode.FAIL, "內容為空");
        }else {
            return new JsonResult(ResultCode.SUCCESS, FileUpload.fileOne(file, UploadType.ARTICLE_IMAGES));
        }
    }


    /**
     * @function 表單提交
     * @param userId
     * @param artContent
     * @param artVideo
     * @return
     */
    @PostMapping("/article/submitArticle")
    public JsonResult submitArticle(@RequestParam(value = "userId", required = true) Integer userId, @RequestParam(value = "artContent", required = true) String artContent, @RequestParam(value = "artVideo", required = false) String artVideo) {
        Article article = new Article();
        if(artContent == null || artContent.length() <= 0) {
            return new JsonResult(ResultCode.FAIL, "內容引數為異常!");
        } else if (artVideo == null || artVideo.length() <= 0) {
            article.setArtVideo("");
        } else {
            article.setArtVideo(artVideo);
        }
        article.setUserId(userId);
        article.setArtContent(artContent);
        article.setArtUploadTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        articleService.insertArticle(article);
        return new JsonResult(ResultCode.SUCCESS, article.getArtId());
    }


    /**
     * @function 圖片提交
     * @param artId
     * @param imgUrl
     * @return
     */
    @PostMapping("/articleImages/submitImages")
    public JsonResult submitImages(@RequestParam("artId") Integer artId, @RequestParam("imgUrl") String imgUrl) {
        ArticleImages images = new ArticleImages();
        images.setArtId(artId);
        images.setImgUrl(imgUrl);
        images.setImgTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        imagesService.insert(images);
        return new JsonResult(ResultCode.SUCCESS, "上傳成功!");
    }
}

檔案上傳類

public class FileUpload {

    /**
     * @function 單檔案上傳
     * @return
     */
    public static String fileOne(MultipartFile file, String fileType){
        // 獲取檔名
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        // 獲取新的檔名
        String fileName = UUID.randomUUID() + suffix;
        String newPath = "";
        // 切換檔案儲存路徑
        if(fileType.equals(UploadType.ARTICLE_VIDEO)) {
            newPath = StaticFilePath.ARTICLE_VIDEO + now() + File.separator + fileName;
        }else if(fileType.equals(UploadType.ARTICLE_IMAGES)) {
            newPath = StaticFilePath.ARTICLE_IMAGES + now() + File.separator + fileName;
        }else if(fileType.equals(UploadType.CAROUSEL_IMAGE)) {
            newPath = StaticFilePath.CAROUSEL + now() + File.separator + fileName;
        }
        // 完整的儲存路徑
        String savePath = StaticFilePath.ROOT_PATH + newPath;
        File saveFile = new File(savePath);
        if(!saveFile.getParentFile().exists()){
            saveFile.getParentFile().mkdirs();
        }
        try {
            file.transferTo(saveFile);
            return StaticFilePath.ROOT_URL + newPath;
        } catch (IOException e) {
            e.printStackTrace();
            return "上傳失敗!";
        }

    }
}

檔案路徑類

// 檔案上傳路徑
public class StaticFilePath {

    // 伺服器根URL
    public static final String ROOT_URL = "你的網址";
    // 伺服器根路徑 (對映在伺服器的路徑)
    final static String ROOT_PATH = File.separator + "home" + File.separator + "kehuischool" + File.separator + "workspace" + File.separator;
//    public static final String ROOT_PATH = "E:\\images" + File.separator;

    // 文章圖片
    public static final String ARTICLE_IMAGES = "article_image" + File.separator;

    // 文章視訊
    public static final String ARTICLE_VIDEO = "article_video" + File.separator;

    //輪播圖
    public static final String CAROUSEL = "carousel" + File.separator;

}