文件上传页面三要素:
1、 form表单提交方式一定是post
2、 form表单的enctype一定是multipart/form-data
3、 form表单中一定要有一个input的type是 file
文件上传一定要有的jar
Commons-io和commons-fileupload
Springmvc文件上传:
1、 springmvc.xml中一定要有 多媒体解析器
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2、 后台Controller中的方法中形参使用MultipartFile类型接收文件,参数的名称一定要和页面上的参数名称保持一致
自己编写的上传文件demo,上传文件至FastDFS服务器,代码如下:
packagedemo;import org.csource.fastdfs.*;public classFastfsDemo {public static void main(String[] args) throwsException {
ClientGlobal.init("G:\\pyg_parent\\pyg_shop_web\\src\\main\\resources\\fastdfs_client.conf");//2、创建一个 TrackerClient 对象。直接 new 一个
TrackerClient trackerClient = newTrackerClient();//3、使用 TrackerClient 对象获取连接,获得一个 TrackerServer 对象
TrackerServer trackerServer =trackerClient.getConnection();//4、创建一个 StorageServer 的引用,值为 null
StorageServer storageServer = null;//5、创建一个 StorageClient 对象,需要两个参数 TrackerServer 对象、StorageServer 的引用
StorageClient storageClient = newStorageClient(trackerServer,storageServer);//6、使用 StorageClient 对象上传图片
String[] strings = storageClient.upload_file("C:\\Users\\o_Osky\\Desktop\\1.png", "png", null);//7、返回数组。包含组名和图片的路径
for(String string : strings) {
System.out.println(string);
}
// storageClient.delete_file("group1", "M00/00/00/wKgRcFV_08OAK_KCAAAA5fm_sy874.conf") 删除文件
} }
需要注意的是:上传文件的路径为绝对路径,在实际应用中,应用相对路径,且demo中new 对象过多,所以封装了工具类,代码如下:
packageutils;importorg.csource.common.NameValuePair;importorg.csource.fastdfs.ClientGlobal;importorg.csource.fastdfs.StorageClient1;importorg.csource.fastdfs.StorageServer;importorg.csource.fastdfs.TrackerClient;importorg.csource.fastdfs.TrackerServer;public classFastDFSClient {private TrackerClient trackerClient = null;private TrackerServer trackerServer = null;private StorageServer storageServer = null;private StorageClient1 storageClient = null;public FastDFSClient(String conf) throwsException {if (conf.contains("classpath:")) {
conf= conf.replace("classpath:", this.getClass().getResource("/").getPath());
}
ClientGlobal.init(conf);
trackerClient= newTrackerClient();
trackerServer=trackerClient.getConnection();
storageServer= null;
storageClient= newStorageClient1(trackerServer, storageServer);
}/*** 上传文件方法
*
Title: uploadFile
*
Description:
*@paramfileName 文件全路径
*@paramextName 文件扩展名,不包含(.)
*@parammetas 文件扩展信息
*@return*@throwsException*/
public String uploadFile(String fileName, String extName, NameValuePair[] metas) throwsException {
String result=storageClient.upload_file1(fileName, extName, metas);returnresult;
}public String uploadFile(String fileName) throwsException {return uploadFile(fileName, null, null);
}public String uploadFile(String fileName, String extName) throwsException {return uploadFile(fileName, extName, null);
}/*** 上传文件方法
*
Title: uploadFile
*
Description:
*@paramfileContent 文件的内容,字节数组
*@paramextName 文件扩展名
*@parammetas 文件扩展信息
*@return*@throwsException*/
public String uploadFile(byte[] fileContent, String extName, NameValuePair[] metas) throwsException {
String result=storageClient.upload_file1(fileContent, extName, metas);returnresult;
}public String uploadFile(byte[] fileContent) throwsException {return uploadFile(fileContent, null, null);
}public String uploadFile(byte[] fileContent, String extName) throwsException {return uploadFile(fileContent, extName, null);
}
}
配置spingmvc文件,配置解析器:
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd">
WriteMapNullValue
WriteDateUseDateFormat
angularjsServer层代码:
app.service("uploadService",function($http){//angularJS的文件上传
this.upload=function(){//html5的对象
var formData = newFormData();
formData.append("file",file.files[0]); //file.files[0] js的取值方式 取到页面的第一个type=”file“ "file"与MultipartFile file 名字一致
return$http({
method:'post',
url:'../upload/uploadFile',
data:formData,
headers: {'Content-Type':undefined}, //写了这一行即声明enctype类型一定是 multipart/form-data
transformRequest: angular.identity //序列化上传的文件
});
}
})
angularController层代码:
$scope.uploadFile = function() {
uploadService.upload().success(function(result) {if(result.flag) {
$scope.imgUrl=result.message;
}else{
alert(result.message);
}
})
}
调用工具类实现文件上传:
packagecom.pyg.shop.controller;importbean.ResultInfo;importorg.springframework.beans.factory.annotation.Value;importorg.springframework.web.bind.annotation.RequestMapping;importorg.springframework.web.bind.annotation.RequestParam;importorg.springframework.web.bind.annotation.RestController;importorg.springframework.web.multipart.MultipartFile;importutils.FastDFSClient;
@RestController
@RequestMapping("/upload")public classUploadController {/** springmvc从properties中获取变量的方式
* application.properties==>upload_server=http://192.168.25.133/**/@Value("${upload_server}")privateString uploadServer;
@RequestMapping("/uploadFile")publicResultInfo uploadFile(MultipartFile file) {try{/** tracker_server=192.168.25.133:22122
**/FastDFSClient fastDFSClient= new FastDFSClient("classpath:fastdfs_client.conf");
String fileName= file.getOriginalFilename();//获取上传文件的相对路径
/** 获取上传文件的扩展名
* png 不带“.” 所以+1
**/String extName= fileName.substring(fileName.lastIndexOf(".") + 1);/** 文件上传成功后,返回文件在服务器中位置
* 为了准确的url需要拼接上服务器ip,ip可能会变动,所以用配置文件加载服务器ip
**/String fileUrl=fastDFSClient.uploadFile(file.getBytes(), extName);return new ResultInfo(true, uploadServer +fileUrl);
}catch(Exception e) {
e.printStackTrace();return new ResultInfo(false, "上传失败");
}
}
}
实现效果如下: