webuploader上传文件,后台Java接收

前台html页面:




Insert title here








	
选择文件

引用的index.js:

$(function() {
	var $list = $("#thelist");
	var $btn = $("#ctlBtn");
	var state = 'pending'; // 上传文件初始化
	var uploader = WebUploader.create({
		swf : 'webuploader/Uploader.swf',
		server : 'http://localhost:8080/Shopping/filecontroller/upload',
		pick : '#picker',
		resize : false
	});
	uploader.on('fileQueued', function(file) {
		$list.append('
' + '

' + file.name + '

' + '

等待上传...

' + '
'); }); uploader.on('uploadProgress', function(file, percentage) { var $li = $('#' + file.id), $percent = $li .find('.progress .progress-bar'); // 避免重复创建 if (!$percent.length) { $percent = $( '
' + '
' + '
' + '
') .appendTo($li).find('.progress-bar'); } $li.find('p.state').text('上传中'); $percent.css('width', percentage * 100 + '%'); }); uploader.on('uploadSuccess', function(file) { $('#' + file.id).find('p.state').text('已上传'); }); uploader.on('uploadError', function(file) { $('#' + file.id).find('p.state').text('上传出错'); }); uploader.on('uploadComplete', function(file) { $('#' + file.id).find('.progress').fadeOut(); }); $btn.on('click', function() { if (state === 'uploading') { uploader.stop(); } else { uploader.upload(); } }); });

后台的Java Controller:

package com.wdg.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
import org.springframework.util.FileCopyUtils;
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.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.wdg.util.BuildJsonOfObject;

@RestController
@RequestMapping("/filecontroller")
public class UploadFileController {

	private Logger log;

	public UploadFileController() {
		this.log = Logger.getLogger(this.getClass());
	}

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@RequestParam("file")MultipartFile files,HttpServletRequest request, HttpServletResponse response) throws IOException {
		JSONObject json=new JSONObject();
		response.setCharacterEncoding("utf-8");
		String msg = "添加成功";
		log.info("-------------------开始调用上传文件upload接口-------------------");
		try{
		String name = files.getOriginalFilename();
		String path = this.getClass().getClassLoader().getResource("/").getPath();
		int index = path.indexOf("Shopping");
		path = path.substring(0, index + "Shopping".length()) + "/WebContent/resources/upload/";
		path = path + File.separator + name;
		File uploadFile = new File(path);
		files.transferTo(uploadFile);
		}catch(Exception e){
			msg="添加失败";
		}
		log.info("-------------------结束调用上传文件upload接口-------------------");
		json.put("msg", msg);
		return BuildJsonOfObject.buildJsonOfJsonObject(json);
	}

	/*private byte[] inputStreamToByte(InputStream is) throws IOException {
		ByteArrayOutputStream bAOutputStream = new ByteArrayOutputStream();
		int ch;
		while ((ch = is.read()) != -1) {
			bAOutputStream.write(ch);
		}
		byte data[] = bAOutputStream.toByteArray();
		bAOutputStream.close();
		return data;
	}*/

	@RequestMapping(value = "/uploadservlet", method = RequestMethod.POST, produces = "text/html;charset=utf-8")
	protected String uploadServlet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		JSONObject json=new JSONObject();
		response.setCharacterEncoding("utf-8");
		String msg = "添加成功";
		log.info("-------------------开始调用上传文件uploadservlet接口-------------------");
		try {
			if (request instanceof MultipartHttpServletRequest) {
				MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;
				List multipartFile = mr.getFiles("myfile");
				if (null != multipartFile && !multipartFile.isEmpty()) {
					MultipartFile file = multipartFile.get(0);
					String name = file.getOriginalFilename();
					String path = this.getClass().getClassLoader().getResource("/").getPath();
					int index = path.indexOf("Shopping");
					path = path.substring(0, index + "Shopping".length()) + "/WebContent/resources/upload/";
					path = path + File.separator + name;
					File uploadFile = new File(path);
					if(FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(uploadFile))>0)
					{
						json.put("path",path);
					}
				
				}
			}
		} catch (Exception e) {
			msg = "上传失败";
		}
		log.info("-------------------结束调用上传文件uploadservlet接口-------------------");
		json.put("msg", msg);
		return BuildJsonOfObject.buildJsonOfJsonObject(json);
	}
}

可以看到的是利用百度的webuploader上传文件还是十分的简单

希望对你有所帮助





你可能感兴趣的:(java,SpringMVC,webuploader)