fastDFS图片上传下载

java文件

js

// 上传合同fastfds
	//var fileUrl = $(‘#fileUrl‘).val();
	addUpload($(‘#path‘));
	function addUpload(fileInput){
		$(fileInput).fileupload({
           url:  ‘uploadingJson.do‘,
           dataType: ‘json‘,
           done: function (e, res) {
               var result =res.result;
               if(result.message != undefined){
            	   bootBoxDialog(result.message);
            	   return false;
               }
               var url=result.data.url;
               $(this).parent().css("background-color", "");
               $(this).parent().find("#pathValue").val(url);
			   $(this).parent().parent().find("a").remove();
			   $(this).parent().parent().find("#del").show();
			   $(this).parent().after(‘<a target="_bank" href="‘+url+‘">  附件查看</a>‘);
			   $(this).parent().after(‘<img  src="readImage.do?imagePath=‘+url+‘">‘);
           },
           progressall: function (e, data) {

           }
       });
	}

  java文件

里面有用fastDFS方法的,和没用fastDFS方法的图片上传

js和其他一样,fastDFS只是配置了一些参数,然后引入自己的包。

package com.guilf.consumer.controller;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;

import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;
import com.guilf.consumer.image.FastDFSClient;
//import com.guilf.project.entity.User;
//import com.guilf.project.service.UserService;

@Controller("imageController")
@RequestMapping("/")
public class ImageController
{
	//@Autowired
	//private UserService userService;

	@RequestMapping("imageInAndOut")
    public String hello(){
        return "imageInAndOut";

    }

	@RequestMapping(value = "uploadingJson", method = RequestMethod.POST)
    @ResponseBody
    public Object upload(HttpServletRequest request, HttpServletResponse response,
                         @RequestParam("file") MultipartFile uploadFile) throws Exception
    {
        String fileId;
        try
        {
            fileId = FastDFSClient.uploadFile(uploadFile.getInputStream(), uploadFile.getOriginalFilename());
        } catch (IOException e)
        {
            throw new Exception("文件上传失败");
        }

        JSONObject attachment = new JSONObject();
        attachment.put("name", uploadFile.getOriginalFilename());
        attachment.put("size", uploadFile.getSize());
        attachment.put("url", fileId);
        String userAgent = request.getHeader("User-Agent");
        //logger.info(userAgent);

        JSONObject rejson = new JSONObject();
        rejson.put("data", attachment);

        if (userAgent.contains("MSIE 9"))
        {
          //  logger.info("是IE浏览器,返回纯文本");
            response.setContentType("text/plain");
            return rejson.toJSONString();
        }

        return rejson;
    }

	//上传文件会自动绑定到MultipartFile中
    @RequestMapping(value="uploadImage",method=RequestMethod.POST)
    public String upload(HttpServletRequest request,
           @RequestParam("description") String description,
           @RequestParam("file") MultipartFile file) throws Exception {

       System.out.println(description);
       //如果文件不为空,写入上传路径
       if(!file.isEmpty()) {
           //上传文件路径
         //  String path = request.getServletContext().getRealPath("/images/");
           String path = "E:\\myEclipseGuilf\\workspace\\iamge";
           //上传文件名
           String filename = file.getOriginalFilename();
           File filepath = new File(path,filename);
           //判断路径是否存在,如果不存在就创建一个
           if (!filepath.getParentFile().exists()) {
               filepath.getParentFile().mkdirs();
           }
           //将上传文件保存到一个目标文件当中
           file.transferTo(new File(path + File.separator + filename));
           return "success";
       } else {
           return "error";
       }
    }

  //上传文件会自动绑定到MultipartFile中AJAX提交的
    @RequestMapping(value="uploadImage_ajax",method=RequestMethod.POST)
    @ResponseBody
    public Object uploadAjax(HttpServletRequest request,
           @RequestParam("file") MultipartFile file) throws Exception {
       //如果文件不为空,写入上传路径
       if(!file.isEmpty()) {
           //上传文件路径
         //  String path = request.getServletContext().getRealPath("/images/");
           String path = "E:\\myEclipseGuilf\\workspace\\iamge";
         //  String path = request.getSession().getServletContext().getRealPath("/images/");
    	 //  String path = request.getContextPath();
           //上传文件名
           String filename = file.getOriginalFilename();
           File filepath = new File(path,filename);
           //判断路径是否存在,如果不存在就创建一个
           if (!filepath.getParentFile().exists()) {
               filepath.getParentFile().mkdirs();
           }
           //将上传文件保存到一个目标文件当中
           file.transferTo(new File(path + File.separator + filename));

           JSONObject attachment = new JSONObject();
           attachment.put("name", filename);
           attachment.put("url",  path + File.separator + filename);
           JSONObject rejson = new JSONObject();
           rejson.put("data", attachment);
           return rejson;
       } else {
           return "error";
       }
    }

    //读图片到前台展示
	@RequestMapping(value = "readImage")
	public void readImage(HttpServletRequest request,HttpServletResponse response,
			@RequestParam("imagePath") String imagePath) {
		//String imagePath = request.getParameter("imagePath");// 图片绝对路径
		try {
			File file = new File(imagePath);
			if (file.exists()) {
				DataOutputStream temps = new DataOutputStream(
						response.getOutputStream());
				DataInputStream in = new DataInputStream(new FileInputStream(
						imagePath));
				byte[] b = new byte[2048];
				while ((in.read(b)) != -1) {
					temps.write(b);
					temps.flush();
				}
				in.close();
				temps.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

  

原文地址:https://www.cnblogs.com/guilf/p/9397572.html

时间: 2024-08-21 01:54:10

fastDFS图片上传下载的相关文章

JSP+Servlet中使用jspsmartupload.jar进行图片上传下载

JSP+Servlet中使用cos.jar进行图片上传 upload.jsp <form action="FileServlet" method="post" enctype="multipart/form-data"> <input type="file" name="myfile"> <input type="text" name="cmt&q

Android开发中使用七牛云存储进行图片上传下载

Android开发中的图片存储本来就是比较耗时耗地的事情,而使用第三方的七牛云,便可以很好的解决这些后顾之忧,最近我也是在学习七牛的SDK,将使用过程在这记录下来,方便以后使用. 先说一下七牛云的存储原理,上面这幅图片是官方给出的原理图,表述当然比较清晰了.可以看出,要进行图片上传的话可以分为五大步: 1. 客户端用户登录到APP的账号系统里面: 2. 客户端上传文件之前,需要向业务服务器申请七牛的上传凭证,这个凭证由业务服务器使用七牛提供的服务端SDK生成: 3. 客户端使用七牛提供的客户端S

WebApi2 文件图片上传下载

Asp.Net Framework webapi2 文件上传与下载 前端界面采用Ajax的方式执行 一.项目结构 1.App_Start配置了跨域访问,以免请求时候因跨域问题不能提交.具体的跨域配置方式如下,了解的朋友请自行略过. 跨域配置:NewGet安装dll Microsofg.AspNet.Cors 然后在App_Start 文件夹下的WebApiConfig.cs中写入跨域配置代码. 1 public static class WebApiConfig 2 { 3 public sta

图片上传-下载-删除等图片管理的若干经验总结3-单一业务场景的完整解决方案

这次完整地介绍图片上传的完整解决方案,如有bug,后续再补充. 一.图片表 CREATE TABLE `photo` ( `id` bigint(10) unsigned NOT NULL AUTO_INCREMENT, `bizid` bigint(11) NOT NULL DEFAULT '-1' COMMENT '业务id,比如项目的id', `cover` int(11) DEFAULT '0' COMMENT '1:是,0:不是', `sort` int(11) DEFAULT '0'

[iOS AFNetworking框架实现HTTP请求、多文件图片上传下载]

简单的JSON的HTTP传输就不说了,看一个简单的DEMO吧. 主要明白parameters是所填参数,类型是字典型.我把这部分代码封装起来了,以便多次调用.也许写在一起更清楚点. #pragma mark - JSON方式post提交数据 - (void)postJSONWithUrl:(NSString *)urlStr parameters:(id)parameters success:(void (^)(id responseObject))success fail:(void (^)(

图片上传-下载-删除等图片管理的若干经验总结2

今天再次思考了下图片上传,觉得昨天的有个细节存在问题. 昨天在码代码的时候,没有去考虑删除临时文件的问题.今天,想增加删除临时文件,发现昨天的代码就有问题了. 上次提到: class PhotoBean { //将要删除的,通常是数据库中的 public List<Photo> toDelete; //将要更新的,都在数据库中,部分最新内容来源于web前端 public List<Photo> toUpdate; //将要增加的,由于上传图片的时候都已经插入了,这个时候可以忽略了

图片上传-下载-删除等图片管理的若干经验总结

图片上传功能很常见,很多人都觉得这个功能很简单,随着要求的提高,这个图片小系统也真是复杂啊. 需求1: 上传,未了达到"大容量存储"."负载均衡"."性能好","有技术含量"等装逼需求,采用了Fastdfs. 注:FastDFS是一个开源的轻量级分布式文件系统,它对文件进行管理. 功能包括:文件存储.文件同步.文件访问(文件上传.文件下载)等,解决了大容量存储和负载均衡的问题. 特别适合以文件为载体的在线服务,如相册网站.视频

ftp上传下载| 图片上传下载

弹出输入文件路径提示*1. Open File Dialog  CALL METHOD cl_gui_frontend_services=>file_open_dialog    CHANGING      file_table  = lt_file  "Table Holding Selected Files      user_action = l_user_action      rc          = l_rc.  IF l_user_action = cl_gui_front

spring boot(十八)集成FastDFS文件上传下载

上篇文章介绍了如何使用Spring Boot上传文件,这篇文章我们介绍如何使用Spring Boot将文件上传到分布式文件系统FastDFS中. 这个项目会在上一个项目的基础上进行构建. 1.pom包配置 我们使用Spring Boot最新版本1.5.9.jdk使用1.8.tomcat8.0. <dependency> <groupId>org.csource</groupId> <artifactId>fastdfs-client-java</art