当前位置:首页 > 代码 > 正文

jsp上传图片的代码(jsp上传图片的代码格式)

admin 发布:2022-12-19 05:51 81


本篇文章给大家谈谈jsp上传图片的代码,以及jsp上传图片的代码格式对应的知识点,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

谁有jsp上传图片的代码了,把上传的图片保存到文件夹 里的,简单点的,谢谢啊,急,

这个比较简单

选择图片的jsp页面的form

form action="doUploadImage.jsp" encType=multipart/form-data method=post

本地选择:

input type="file" name="selPicture"

style="width: 330px; height: 23px; font-size: 16px"

input type="submit" name="upload" id="upload" value="上传"

style="width: 70px; height: 25px"

/form

接收页面

%@ page language="java" import="java.util.*,com.jspsmart.upload.*,java.io.*"

pageEncoding="GBK"%

!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

html

head

titleMy JSP 'doUploadImage.jsp' starting page/title

/head

body

%

request.setCharacterEncoding("GBK");

long size = 5 * 1024 * 1024;//允许上传最大值为5MB

String fileType = "jpg,gif,JPG";//允许上传文件类型

String imgName = null;//图片名称

byte[] data = null;//数据

String filePath = "";//文件路径

//得到服务器目录webroot下的ImageFiles目录的完整路径

String path = super.getServletContext().getRealPath("/Image");

System.out.println(path);

SmartUpload su = new SmartUpload();

//初始化

su.initialize(pageContext);

su.setMaxFileSize(size);

su.setAllowedFilesList(fileType);

su.setCharSet("GBK");

//上载文件

su.upload();

System.out.println(su.getSize());

su.getRequest();

//循环取得所有上载的文件

Files files = su.getFiles();

if (files != null) {

//如果文件路径不存在则生成路径

java.io.File fileDir = new java.io.File(path);

System.out.println("存在");

if (!fileDir.exists()) {

fileDir.mkdirs();

System.out.println("不存在");

}

System.out.println(files.getCount());

//取出文件

for (int i = 0; i files.getCount(); i++)

{

com.jspsmart.upload.File file = files.getFile(i);

if (file.isMissing()) continue;

if ("selPicture".equals(file.getFieldName())) {

String type = file.getFilePathName();

type = type.substring(type.lastIndexOf("."));

imgName = UUID.randomUUID().toString();//生成uuid作为图片的名称

imgName += type;

filePath = path + "/" + imgName;

//保存到指定文件

file.saveAs(filePath);

//读取文件

data = readFile(filePath);

break;

}

}

}

if (data == null) {

out.print("没有图片");

} else {

out.print("图片上传成功");

}

%

%!byte[] readFile(String filePath) {

ByteArrayOutputStream bos = null;

try {

FileInputStream fs = new FileInputStream(filePath);

bos = new ByteArrayOutputStream(5 * 1024 * 1024);

byte[] b = new byte[1024];

int len;

while ((len = fs.read(b)) != -1) {

bos.write(b, 0, len);

}

fs.close();

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

if (bos == null) {

return null;

} else {

return bos.toByteArray();

}

}

%

%=request.getParameter("name") %

/body

/html

有问题q我 379726806

后面data那一段时测试的 用的时候删除掉 这是我写的一个测试小工程 在项目里面用的时候是把接收图片放在servlet中的

我也是才搞了一个图片上传的东东

java 求jsp上传图片到服务器代码

提交页面表单

form action="up.jsp" enctype="multipart/form-data" method="post"

input type="file" name="file"

input type="submit" value="确定"

/form

上传页面up.jsp

%@page import="java.io.FileWriter"%

%@ page language="java" contentType="text/html; charset=UTF-8"

import="java.io.*"

pageEncoding="UTF-8"%

%

/**

协议头四行内容

45 -----------------------------7de231211204c4

80 Content-Disposition: form-data; name="file"; filename="xx.txt"

26 Content-Type: text/plain

2

标记文件结尾

-----------------------------7de231211204c4--

**/

ServletInputStream sin = request.getInputStream();

byte[] buffer = new byte[1024 * 8];

int length = 0, row = 0;

String mark = "";

String filename = "";

while ((length = sin.readLine(buffer, 0, buffer.length)) 0) {

out.println(length + " " + new String(buffer, 0, length, "UTF-8") + "br");

String s = new String(buffer, 0, length, "UTF-8");

if (row == 0)

mark = s.trim();

else if (s.indexOf("filename=") 0) {

int end = s.lastIndexOf("\"");

int start = s.substring(0, end).lastIndexOf("\"");

filename = s.substring(start + 1, end);

} else if ("".equals(s.trim()))

break;

row ++;

}

out.println("filename: " + filename + "br");

filename = request.getRealPath("/") + "../" + filename;

FileOutputStream fout = new FileOutputStream(filename);

while ((length = sin.readLine(buffer, 0, buffer.length)) 0) {

String s = new String(buffer, 0, length);

if (s.startsWith(mark))

break;

fout.write(buffer, 0, length);

}

fout.flush();

fout.close();

File f = new File(filename);

out.println(f.exists());

out.println(f.getAbsolutePath());

%

jsp怎么上传图片?求代码!

Apache commons-fileupload是一个很好的文件上传工具,最近使用commons-fileupload实现了图片的上传及显示,可将图片保存在指定的文件夹中,也可以将图片存放在数据库,并支持四种常用的图片格式:jpg,png,gif,bmp。

首先,跟上传一般文件一样,需要写一个servlet来处理上传的文件,你可以修改保存路径或选择将图片保存在数据库中,只需要做简单的修改就行了,servlet代码如下:

FileUploadServlet.java

java 代码 package com.ek.servlet; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import com.ek.image.ImageUtil; public class FileUploadServlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; private static String filePath = ""; /** * Destruction of the servlet.

*/ public void destroy() { super.destroy(); // Just puts "destroy" string in log // Put your code here } /** * The doPost method of the servlet.

* * This method is called when a form has its tag value method equals to * post. * * @param request * the request send by the client to the server * @param response * the response send by the server to the client * @throws ServletException * if an error occurred * @throws IOException * if an error occurred */ public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html; charset=UTF-8"); DiskFileItemFactory factory = new DiskFileItemFactory(); // maximum size that will be stored in memory factory.setSizeThreshold(4096); // the location for saving data that is larger than getSizeThreshold() factory.setRepository(new File(filePath)); ServletFileUpload upload = new ServletFileUpload(factory); // maximum size before a FileUploadException will be thrown upload.setSizeMax(1000000); try { List fileItems = upload.parseRequest(req); Iterator iter = fileItems.iterator(); // Get the file name String regExp = ".+\\\\(.+\\.?())$"; Pattern fileNamePattern = Pattern.compile(regExp); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (!item.isFormField()) { String name = item.getName(); long size = item.getSize(); if ((name == null || name.equals("")) size == 0) continue; Matcher m = fileNamePattern.matcher(name); boolean result = m.find(); if (result) { try { // String type = // m.group(1).substring(m.group(1).lastIndexOf('.')+1); InputStream stream = item.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] b = new byte[1000]; while (stream.read(b) 0) { baos.write(b); } byte[] imageByte = baos.toByteArray(); String type = ImageUtil.getImageType(imageByte); if (type.equals(ImageUtil.TYPE_NOT_AVAILABLE)) throw new Exception("file is not a image"); BufferedImage myImage = ImageUtil .readImage(imageByte); // display the image ImageUtil.printImage(myImage, type, res .getOutputStream()); // save the image // if you want to save the file into database, do it here // when you want to display the image, use the method printImage in ImageUtil item.write(new File(filePath + "\\" + m.group(1))); stream.close(); baos.close(); } catch (Exception e) { e.printStackTrace(); } } else { throw new IOException("fail to upload"); } } } } catch (IOException e) { e.printStackTrace(); } catch (FileUploadException e) { e.printStackTrace(); } } /** * Initialization of the servlet.

* * @throws ServletException * if an error occure */ public void init() throws ServletException { // Change the file path here filePath = getServletContext().getRealPath("/"); } 请打勾满意,原创谢谢

通过JSP怎样上传图片到服务器

1.限制文件上传类型只能是图片

function checkFileType(name,file){

var extArray = new Array(".doc",".docx");

var allowSubmit = false;

if (!file){

return;

}

while (file.indexOf("\\") != -1){

file = file.slice(file.indexOf("\\") + 1);

}

var ext = file.slice(file.indexOf(".")).toLowerCase();

for (var i = 0; i extArray.length; i++) {

if (extArray[i] == ext){

allowSubmit = true;

break;

}

}

if(!allowSubmit){

alert("只能上传以下格式的文件:"+ (extArray.join("")) + "\n请重新选择再上传.");

document.getElementById(name).value = "";

}

}

其中:extArray是要求文件类型。可自行定义。

2.引入jQuery外部文件

jquery-2.1.4.min.js

3.编写js代码

$(function () {

$('#txtfilePath1').uploadReview({

width: 350,

height: 350,

target: '#uploadReview1_content'

});

});

其中:txtfilePath1是input:file。width,height是预览图片的宽度和高度。target是显示预览图片的位置。

4.编写jsp页面代码

body

input type="text" class="yourClassName" name="filePath1" id="filePath1"/

input type="file" id="txtfilePath1" name="txtfilePath1" style="display:none;"

input type="button" onclick="txtfilePath1.click()" id="fileup1" name="fileup1" class="searchThing"value="上传"

/body

注: 这个是很久以前在网上看到的,就整理了下来,但是这么久都没用过,所以也没调试过,你自己试一试研究研究, 再来网上很多博客里,他们写的很详细的,可以去看看

关于jsp上传图片的代码和jsp上传图片的代码格式的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。

版权说明:如非注明,本站文章均为 AH站长 原创,转载请注明出处和附带本文链接;

本文地址:http://ahzz.com.cn/post/3384.html


取消回复欢迎 发表评论:

分享到

温馨提示

下载成功了么?或者链接失效了?

联系我们反馈

立即下载