上传图片(fastDFS)

前台js代码:

//定义service服务层
app.service("uploadService", function($http) {
    //上传方法
    this.uploadFile = function() {
        //创建form表单对象
        var formData = new FormData();
        //把表单对象封装表单数据
        formData.append("file", file.files[0]);
        
        return $http({
            method : 'POST',
            url : "../upload/pic",
            data : formData,
            headers : {
                'Content-Type' : undefined
            },
            transformRequest : angular.identity
        });
    }

});


表现层代码:

public class UploadController {
        @Value("${FAST_URL}")
        private String FAST_URL;//文件服务器地址
        
        @RequestMapping("/pic")
        public PygResult upload(MultipartFile file){
            //1、取文件的扩展名
            String originalFilename = file.getOriginalFilename();
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            
            //2、创建一个FastDFS的客户端
            try {
                FastDFSClient fastDFSClient = new FastDFSClient("classpath:config/client.conf");
            //3、执行上传处理
                String path = fastDFSClient.uploadFile(file.getBytes(), extName);
            //4、拼接返回的url和ip地址,拼装成完整的url
                String url = FAST_URL + path;
                return new PygResult(true,url);
            } catch (Exception e) {
                e.printStackTrace();
                return new PygResult(true,"上传失败");
            }
        }

springmvc的配置文件中:

<!-- 配置多媒体解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 设定文件上传的最大值5MB,5*1024*1024 -->
        <property name="maxUploadSize" value="5242880"></property>

    </bean>





猜你喜欢

转载自blog.csdn.net/doityourselfagain/article/details/80809817