文件上传 fileupload

</pre>文件上传做一个笔记。<p></p><p>页面导入fileupload的插件包 jquery.fileupload.js、jquery.fileupload-process.js、jquery.fileupload-validate.js;</p><p>放一个input的元素 </p><p></p><pre name="code" class="html"><form class="hide">
	<input id="fileupload" type="file" name="imageFile" />
</form>
js代码

$('#'+fileinputid).fileupload({
		url:window.contextPath+url,
		type : 'POST',
		dataType : 'json',
		progressall: function (e, data) {//进度条
          //console.log(data);
		 var progress = parseInt(data.loaded / data.total * 100, 10);
	        $('.progress .progress-bar').css(
	            'width',
	            progress + '%'
	        );
	        $('.progress .progress-bar').text(progress + '%');
	    },
		add:function(e,data){//在选中文件开始上传之前添加一个进度条的显示域
			var html = '<div class="modal fade" id="myModal">\
					  		<div class="modal-dialog" >\
						    <div class="modal-content">\
						      <div class="modal-body">\
								<div class="progress">\
								  <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">\
								    0%\
								  </div>\
								</div>\
						      </div>\
						    </div>\
						  </div>\
						</div>';
			$('body').append(html);
			$('#myModal').modal();
			data.submit();
		},
		done : function(e, data) {
			$("#myModal").remove();
			if (data._response.result.success) {
				callback(data);
			} else {
				ZL.alert("faild");
			}
	}});

java后台代码的处理

/**
     * 文件上传
     *
     * @param module    模块名,对应文件目录
     * @param imageFile 上传的文件流
     * @return
     */
    @RequestMapping(value = {"/file/{module}/upload.sj"})
    @ResponseBody
    public ResultView upload(@PathVariable String module, MultipartFile imageFile) {
        ResultView rv = new ResultView();
        rv.setMsg("上传文件失败!");
        try {
            if (null != imageFile) {
                String filepath = saveRsource(module, imageFile);
                rv.setSuccess(true);
                rv.setData(filepath);
            }
        } catch (IOException e) {
            logger.error(e.getLocalizedMessage(), e);
        }
        return rv;
    }

/**
     * 保存文件
     *
     * @param module   目录名
     * @param userFile 文件流
     * @return
     * @throws IOException
     */
    private String saveRsource(String module, MultipartFile userFile) throws IOException {
        String originalFilename = userFile.getOriginalFilename(); // 原始文件名
        String fileName = UUIDGenerator.getUUID() + "." + FileUtils.getFileExtension(originalFilename); // 存储文件名
        String relativePath = module + "/" + DateUtils.format(new Date(), DateUtils.YYYYMM) + "/" + fileName; // 相对路径
        String filePath = fileService.getFileserver() + relativePath;// 绝对路径
        File file = new File(filePath);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        FileCopyUtils.copy(userFile.getBytes(), file);
        return originalFilename + "," + relativePath;
    }



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
commons-fileupload是一个用于处理文件上传的Java类库。它提供了简单易用的API,可以用于实现文件上传功能。要使用commons-fileupload,你需要进行以下步骤: 1. 导入commons-fileupload库:下载commons-fileupload库的jar文件,并将其添加到你的项目中。 2. 创建Servlet或Controller类:创建一个处理文件上传的Servlet或Controller类。 3. 创建DiskFileItemFactory对象:使用DiskFileItemFactory类创建一个文件项工厂对象,设置临时文件存储路径和内存缓冲区大小。 4. 创建ServletFileUpload对象:使用ServletFileUpload类创建一个文件上传对象,并设置文件上传的大小限制和字符编码。 5. 解析请求:使用ServletFileUpload对象的parseRequest()方法解析请求,得到FileItem对象的列表。 6. 处理文件:遍历FileItem对象的列表,对每个文件项进行处理。你可以判断文件项是否是普通字段还是文件,以及获取字段名称、文件名、文件大小等信息。 以下是一个简单的示例代码: ```java import org.apache.commons.fileupload.*; import org.apache.commons.fileupload.disk.*; import org.apache.commons.fileupload.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class FileUploadServlet extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (item.isFormField()) { // 处理普通字段 String fieldName = item.getFieldName(); String fieldValue = item.getString(); // ... } else { // 处理文件 String fieldName = item.getFieldName(); String fileName = item.getName(); long fileSize = item.getSize(); // ... } } // 文件上传成功 response.getWriter().println("文件上传成功!"); } catch (FileUploadException e) { // 文件上传失败 response.getWriter().println("文件上传失败!"); } } } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值