本文以上传图片为例
小程序代码:
startUpload: function(){
wx.chooseImage({
success: function (res) {
var tempFilePaths = res.tempFilePaths
console.log(tempFilePaths)
wx.uploadFile({
url: 'http://localhost:8080/upload/fileUpload' , //仅为示例,非真实的接口地址
filePath: tempFilePaths[0],
name: "file",
header: {
"Content-Type": "multipart/form-data"
},
formData: {
"user": "test",
},
success: function (res) {
var data = res.data
console.log(data)
//do something
}
})
}
java后端代码:
package com.contoller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.apachemons.io.FileUtils;
import org.apachemons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.tool.FileUtil;
@RestController
@RequestMapping("/upload")
public class UploadFileContoller {
private static final Logger LOG = LoggerFactory
.getLogger(UploadFileContoller.class);
@PostMapping("/fileUpload")
public String uploadMusicFile(HttpServletRequest request,@RequestParam("file")MultipartFile[] files){
LOG.info("进入上传...");
String uploadPath="E:/pic/";//存放到本地路径(示例)
if(files!=null && files.length>=1) {
BufferedOutputStream bw = null;
try {
String fileName = files[0].getOriginalFilename();
//判断是否有文件
if(StringUtils.isNoneBlank(fileName)) {
//输出到本地路径
File outFile = new File(uploadPath + UUID.randomUUID().toString()+ FileUtil.getFileType(fileName)); LOG.info("path=="+uploadPath + UUID.randomUUID().toString()+ FileUtil.getFileType(fileName)); FileUtils.copyInputStreamToFile(files[0].getInputStream(), outFile); } } catch (Exception e) { e.printStackTrace(); } finally { try { if(bw!=null) {bw.close();} } catch (IOException e) { e.printStackTrace(); } } }return "success";}}
public static String getFileType(String filename){
if(filename.endsWith(".jpg") || filename.endsWith(".jepg")){
return ".jpg";
}else if(filename.endsWith(".png") || filename.endsWith(".PNG")){
return ".png";
} else{
return "application/octet-stream";
}
}
更多推荐
微信小程序wx.uploadFile 上传实例(附带java后端代码)
发布评论