After the JS Form form submits the file, customize the jump or prompt

After the form is submitted, the custom page jumps or prompts the content

I found the js request code and html code on the Internet, but when I wanted to look for it later, I couldn't find it. So write this blog for the record.

Will not explain, everything looks at the code.

"HTML" code:

<div class="three-line-power-view">
	<!-- Upload schematic form-->
	<form id="power-view-file-form" enctype="multipart/form-data" action="aaa" method="post" target="rfFrame">
		<input type="file" class="power-view-file-image" name="file" />
		<input type="submit" class="power-view-file-submit" style="cursor: pointer;width:64px;" value="提交" />
		<!-- Image upload display area-->
		<div class="three-line-power-view-file"> </div>
	</form>
	<iframe id="rfFrame" name="rfFrame" src="about:blank" style="display:none;"></iframe> 
</div>
The form sets the target attribute, which refers to the id of the <iframe> below. I don't know why.

If you upload a picture to preview the effect

$(function() {
	$('[type=file]').change(function(e) {
		var file = e.target.files[0];
	        preview1(file);
	});
});
// preview picture
function preview1(file) {
	var img = new Image(), url = img.src = URL.createObjectURL(file);
	var $img = $(img);
	img.onload = function() {
	        URL.revokeObjectURL(url);
	        $('.three-line-power-view-file').empty().append($img);
	}
}
function preview2(file) {
	var reader = new FileReader();
	reader.onload = function(e) {
		var $img = $('<img>').attr("src", e.target.result);
	 	$('.three-line-power-view-file').empty().append($img);
	}
	reader.readAsDataURL(file);
}

There are two ways to preview images.

js request

// Click submit to prevent form submission
$(".power-view-file-submit").click(function(){
	var options = {
	      url : 'aaa', // request path, same as action of form
	      type : 'post',
	      beforeSend : function(xhr){//Before the request
	              var index = layer.load(1, {
	                    shade: [0.5,'#000'] //Black background with 0.5 transparency
	              });
	      },
	      success : function(result) {
	              // Upload what you want to do successfully
	      },
	      complete : function(result){//Request completed
	              //question box
	      	      layer.confirm('Advertiser modified successfully! The page will jump to the list page.', {
	               		btn: ['OK'] //Button
	              },
	              function(){
	                        window.location.href = "www.baidu.com";// page jump after completion
	              });
	      } ,
	      error : function(xhr, status, msg) {
	              alert("Status code"+status+"; "+msg)
	              layer.msg('Loading..');
	      }
};
$("#power-view-file-form").ajaxSubmit(options);

The complete and error methods can be omitted, and all judgments only need to be done in the success method.

Controller controller, upload

	@ResponseBody
	@RequestMapping(value = "aaa", method = { RequestMethod.POST })
	public Map<String, Object> aaa(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request) {
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> retMap = new HashMap<String, Object>();
		Boolean boo = true;
		
		try {
			if (file.isEmpty()) {
				boo = false;
				map = StringUtil.retParam(boo, "Please select a picture", retMap);
			} else {
				// 1. Get the new file name
				// get the original filename
				String originalFileName = file.getOriginalFilename();
				// get the file extension
				String suffix = FilenameUtils.getExtension(originalFileName);
				if (!(suffix.equals("jpg") || suffix.equals("bmp") || suffix.equals("gif") || suffix.equals("png"))) {
					boo = false;
					map = StringUtil.retParam(boo, "Please select the correct format file", retMap);
				}
				else {
					// construct new filename
					String newFileName = System.currentTimeMillis() + "." + suffix;
					// 2. Determine whether the directory created and uploaded exists, if not, add a new folder
					File uploadDir = new File(request.getSession().getServletContext().getRealPath("/img"));
					if (!uploadDir.exists() || !uploadDir.isDirectory()) {
						uploadDir.mkdirs();
					}
					// 3. Copy the file stream to the new file in the upload directory
					File uploadFile = new File(uploadDir.getAbsolutePath() + "/" + newFileName);
					InputStream inputStream = file.getInputStream();
					OutputStream outputStream = new FileOutputStream(uploadFile);
					IOUtils.copy(inputStream, outputStream);
					// close the stream
					IOUtils.closeQuietly(inputStream);
					IOUtils.closeQuietly(outputStream);
					String fileUrl = request.getContextPath() + "/img/" + newFileName;
					retMap.put("fileUrl", fileUrl);
					map = StringUtil.retParam(boo, "Picture uploaded successfully", retMap);
				}
			}
		} catch (Exception e) {
			boo = false;
			map = StringUtil.retParam(boo, "Server exception", retMap);
		}
		
		return map;
	}

There are many online about uploading and downloading codes. I just need to upload here.


The above is the content of the page jump after js controls the form form submission.

If you copy the code and run, you will find that there is an error, that is because you need to download a plugin jQuery-form.js, I can't find the download path, so the download is not provided here.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325364552&siteId=291194637
Recommended