小程序前端上传文件的js代码
wx.uploadFile({
url: 'https://xxxx',//这是你自己后台的连接
filePath: tempFilePath,
name:"file",//后台要绑定的名称
header: {
"Content-Type": "multipart/form-data"
},
//参数绑定
formData:{
id: '10000',
},
success:function(ress){
console.log('上传成功,返回内容是: '+ress.data);
},
fail: function(ress){
console.log("。。上传服务器 失败");
}
})
java 后端的接收方法的代码
注: 其中FileUtils 的包是 import org.apache.commons.io.FileUtils; 自己可以去maven仓库找依赖或jar包
@RequestMapping(value = "/xxx", produces = "application/json")
public String wxSubject(HttpServletRequest request,
@RequestParam("file") MultipartFile files) {
String id= "";
try {
id= request.getParameter("id");
System.out.println("id="+id);
}catch (Exception e){
e.printStackTrace();
}
// 构建上传目录路径
// request.getServletContext().getRealPath("/upload");
String uploadPath = "/opt/temp";//你自己保存音频的URL;
// 如果目录不存在就创建
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
// 获取文件的 名称.扩展名
String oldName = files.getOriginalFilename();
String extensionName = "";
// 获取原来的扩展名
if ((oldName != null) && (oldName.length() > 0)) {
int dot = oldName.lastIndexOf('.');
if ((dot > -1) && (dot < (oldName.length() - 1))) {
extensionName = oldName.substring(dot);
}
}
// 构建文件名称
String fileName = System.currentTimeMillis() + "_" + System.nanoTime()
+ extensionName;
// 构建文件路径
String filePath = uploadPath + File.separator + fileName;
// 保存文件
try {
FileUtils.writeByteArrayToFile(new File(filePath),
files.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("接收文件成功 "+filePath);
return "ok";
}